Showing posts with label decimals. Show all posts
Showing posts with label decimals. Show all posts

Sunday, February 12, 2012

Convert decimals and money to fixed length varchar format.

I am trying to convert decimals and money data types to a universal format and convert to varchar. The format is:

+00.000000

The format must be exactly this format.
The sign must always be present.
There must always be two numbers to the left of the decimal.
There must always be six to the right.
No matter the value, round to six decimals.

Examples:

1.123 : +01.123000
-4 : -04.000000
.98672385 : +00.986724

I have tried every combo of Convert, Cast, Right, etc and every time it doesn't seem to work.

Any ideas?

It is recommended to do the formating in the presentation layer. Try:

select

case when sign(c1) < 0 then '-' else '+' end +

right('00' + str(abs(c1), 8, 6), 9)

from

(

select 1.123 as c1

union all

select -4

union all

select .98672385

) as t

AMB

|||Try this

Code Snippet

declare @.num decimal(18,6)

SET @.num = .98672385

SELECT FmtNum = CASE WHEN @.num < 0 THEN '-' ELSE '+' END +
RIGHT('00'+CONVERT(varchar(9),CONVERT(decimal(9,6),ABS(@.num))),9)

|||You rock.

Thanks. It works great.