可能重复: c# - 我该如何圆一个十进制值2小数位(输出页)
我试图让我的小数,显示有四个小数位。该DB舍我数到4位小数,但它返回尾随0(由于该领域的小数precision)的数量,所以像9.45670000。然后,当我做到这一点:
的String.Format({0:#,#####},decimalValue);
我得到的页面上的输出为9.4567,这正是我想要的。
然而,如果从数据库返回的数是9.45600000,执行格式后的输出为9.456
但我需要显示为9.4560
如何格式化我的小数,使小数位数总是有四个?
更新:另外,就是有可能使用一个变量(而不是0.0000),如果我想动态确定的小数位数?
解决方案 的String.Format({0:N4},decimalValue);
标准数字格式字符串
自定义数字格式字符串
要动态设置precision你可以做到以下几点:
双值= 9.4560000;
INT precision = 4;
字符串格式=的String.Format({{0:N {0}}},precision);
字符串的valueString =的String.Format(格式,值);
Possible Duplicate: c# - How do I round a decimal value to 2 decimal places (for output on a page)
I'm trying to get my decimals to display with four decimal places. The DB rounds my number to 4 decimal places, but it returns the number with trailing 0s (due to the decimal precision of the field), so something like 9.45670000. Then, when I do this:
string.Format("{0:#,#.####}", decimalValue);
The output I get on the page is 9.4567, which is what I want.
However, if the number returned from DB is 9.45600000, the output after doing the format is 9.456
But what I need to display is 9.4560
How do I format my decimal, so that the number of decimal places is always four?
UPDATE: Also, is it possible to use a variable (instead of .0000) if I wanted the number of decimal places to be determined dynamically?
解决方案string.Format("{0:N4}",decimalValue);
Standard Numeric Format Strings
Custom Numeric Format Strings
To set the precision dynamically you can do the following:
double value = 9.4560000;
int precision = 4;
string format = String.Format("{{0:N{0}}}",precision);
string valuestring = String.Format(format, value);
相关推荐
最新文章