I'm worried about my result in converting the numbers to non-decimal and comma separated. I need to achieve proper formatting and rounding the numbers to currency as you can see in the examples below. Please help me.
select sum([TRANSACTION_PRICE]) from [dw_property_detail]
Wrong Result: 520400958.9
Correct Result: 520,400,959
select sum(nullif([ACTUAL_SIZE],0)) from [dw_property_detail]
Wrong Result: 25595.5
Correct Result: (25,596)
select (Min(TRANSACTION_PRICE/ACTUAL_SIZE)) from [dw_property_detail]
Wrong Result: 3241412.6
Correct Result: ($3,241,413)
Given that it is 2017, I'd say there are two correct answers.
FORMAT
function introduced in 2012 as needed, with the appropriate code to output your desired results. I'm sure many would agree that formatting belongs in the presentation layer.
That said, the following should help. I should also add that Format() has some great functionality, it is NOT known to be a performer.
Declare @YourTable table (SomeVal decimal(18,2))
Insert Into @YourTable values
(-3241412.6),
(520400958.9)
Select Format(abs(round(SomeVal,0)),IIF(SomeVal<0,'($#,###)','$#,###'))
From @YourTable
Returns
($3,241,413)
$520,400,959
As mentioned formatting should be left to the client but you can convert your amount to decimal, which will round it up, then convert it to money and use formatting of 1 to add the commas. You can get rid of .00 with substring if you want
select convert(varchar(50), convert(money, convert(decimal, YourValue)), 1)
1 Commas every three digits to the left of the decimal point, and two digits to the right of the decimal point; for example, 3,510.92.
Or:
select '$ ' + reverse(stuff(reverse(convert(varchar(50), convert(money, convert(decimal, YourValue)), 1)), 1, 3, ''))
It so tough to remember so many things,
Declare @YourTable table (SomeVal decimal(18,2))
Insert Into @YourTable values
(3241412.6),
(520400958.9),(25595.5)
select FORMAT( round(SomeVal,0), 'C', 'en-us')
from @YourTable
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.