Answers:
您需要做的第一件事是使用decimal
类型而不是float
价格。float
为此使用绝对是不可接受的,因为它不能准确表示大多数十进制小数。
完成此操作后,Decimal.Round()
可以将其舍入到2位。
String.Format("{0:#,###.##}", value)
来自C#中的字符串格式的一个更复杂的示例:
String.Format("{0:$#,##0.00;($#,##0.00);Zero}", value);
如果通过1243.50,将输出“ $ 1,240.00”。如果数字为负,则将输出相同的格式,但在括号中;如果数字为零,则将输出字符串“零”。
这是针对您要使用插值字符串的情况。我之所以这样发布,是因为我厌倦了反复试验,最终每次需要格式化一些标量时都会浏览大量文档。
$"{1234.5678:0.00}" "1234.57" 2 decimal places, notice that value is rounded
$"{1234.5678,10:0.00}" " 1234.57" right-aligned
$"{1234.5678,-10:0.00}" "1234.57 " left-aligned
$"{1234.5678:0.#####}" "1234.5678" 5 optional digits after the decimal point
$"{1234.5678:0.00000}" "1234.56780" 5 forced digits AFTER the decimal point, notice the trailing zero
$"{1234.5678:00000.00}" "01234.57" 5 forced digits BEFORE the decimal point, notice the leading zero
$"{1234.5612:0}" "1235" as integer, notice that value is rounded
$"{1234.5678:F2}" "1234.57" standard fixed-point
$"{1234.5678:F5}" "1234.56780" 5 digits after the decimal point, notice the trailing zero
$"{1234.5678:g2}" "1.2e+03" standard general with 2 meaningful digits, notice "e"
$"{1234.5678:G2}" "1.2E+03" standard general with 2 meaningful digits, notice "E"
$"{1234.5678:G3}" "1.23E+03" standard general with 3 meaningful digits
$"{1234.5678:G5}" "1234.6" standard general with 5 meaningful digits
$"{1234.5678:e2}" "1.23e+003" standard exponential with 2 digits after the decimal point, notice "e"
$"{1234.5678:E3}" "1.235E+003" standard exponential with 3 digits after the decimal point, notice "E"
$"{1234.5678:N2}" "1,234.57" standard numeric, notice the comma
$"{1234.5678:C2}" "$1,234.57" standard currency, notice the dollar sign
$"{1234.5678:P2}" "123,456.78 %" standard percent, notice that value is multiplied by 100
$"{1234.5678:2}" "2" :)
绩效警告
插值字符串很慢。以我的经验,这是顺序(从快到慢):
value.ToString(format)+" blah blah"
string.Format("{0:format} blah blah", value)
$"{value:format} blah blah"