This is actually a (not very elegant) solution to a problem I had trying to return a float in to a varchar column when doing a union from a dummy_table with some fudged data totals.

In order to get the float to a string, I used the following function in SQL server 2008 (which I found on SO):

str(sum(<float_column>),25,5)

This left lots of leading spaces and trailing zeroes, which was undesirable. I used the following strings to test the formatting with a dummy table (note that there are 24 preceding spaces that don't show):

  • ' 8.50000'
  • ' 0.50000'
  • ' 8.00000'

I used the following functions to get the desired format:

select replace(rtrim(replace(replace(rtrim(replace(ltrim(
'            8.0000'),'0',' ')),' ','0'),'.',' ')),' ','.') from dummy_table;

This works in the following order:

  1. LTRIM trims empty space to the left.
  2. Replace all zeroes with empty spaces.
  3. RTRIM trims these empty spaces from the right.
  4. Replace all spaces with zeroes.
  5. Replace the dot with space.
  6. Trim all space from the right (to get rid of trailing dot if exists).
  7. Replace spaces with dots (to put dot in the correct place if exists).

If you guys can think of a nicer way to do it, let me know!

有帮助吗?

解决方案

round should work for this.

select round(8.5000000000,5)

http://sqlfiddle.com/#!3/1fa93/8845

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top