简体   繁体   English

如何在T-SQL中格式化和舍入数字?

[英]How to do Formatting and Rounding numbers in T-SQL?

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 错误的结果: 520400958.9
Correct Result: 520,400,959 正确的结果: 520,400,959

select sum(nullif([ACTUAL_SIZE],0)) from [dw_property_detail]

Wrong Result: 25595.5 错误的结果: 25595.5
Correct Result: (25,596) 正确的结果: (25,596)

select (Min(TRANSACTION_PRICE/ACTUAL_SIZE)) from [dw_property_detail]

Wrong Result: 3241412.6 错误的结果: 3241412.6
Correct Result: ($3,241,413) 正确的结果: ($3,241,413)

Given that it is 2017, I'd say there are two correct answers. 鉴于现在是2017年,我想说两个正确的答案。

  1. Use the FORMAT function introduced in 2012 as needed, with the appropriate code to output your desired results. 根据需要使用2012年引入的FORMAT函数,并使用适当的代码输出所需的结果。
  2. Formatting should be done client side when possible. 尽可能在客户端进行格式化。

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. 我还应该补充一点,Format()具有一些强大的功能,众所周知它不是表演者。

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. 如前所述,格式应留给客户,但您可以将金额转换为十进制,这将四舍五入,然后将其转换为货币,并使用格式1来添加逗号。 You can get rid of .00 with substring if you want 如果需要,您可以使用子字符串摆脱.00

select convert(varchar(50), convert(money, convert(decimal, YourValue)), 1)

money format 货币格式

1 Commas every three digits to the left of the decimal point, and two digits to the right of the decimal point; 1小数点后每三位逗号,小数点后右两位。 for example, 3,510.92. 例如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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM