Difference between ToString("N2") and ToString("0.00")
What is the difference between 开发者_StackOverflow中文版ToString("N2")
and ToString("0.00")
?
From Standard Numeric Format Strings
The number is converted to a string of the form "-d,ddd,ddd.ddd…", where '-' indicates a negative number symbol if required, 'd' indicates a digit (0-9), ',' indicates a thousand separator between number groups, and '.' indicates a decimal point symbol.
It would seem that N
will include thousands separators, whereas 0.00
will not.
See also Custom Numeric Format Strings
It's all about the decimal places
N2
will work the same way for 500.00, but when you have 5000.00, N2
will display as
5,000.00
instead of
5000.00
See Standard Numeric Format Strings for more information.
Basically, ToString("N2")
will use the CultureInfo
to format the number. This means that your thousands separator might be different depending on the used CultureInfo
. You can also pass the desired CultureInfo
if you want.
Both give you two decimal places, but you can see the difference easily if you check larger numbers:
var d = 1234567.89;
for (var i = 0; i < 10; ++i) {
Console.WriteLine(d.ToString("N2") + "\t" + d.ToString("0.00"));
d /= 10.0;
}
outputs
1.234.567,89 1234567,89
123.456,79 123456,79
12.345,68 12345,68
1.234,57 1234,57
123,46 123,46
12,35 12,35
1,23 1,23
0,12 0,12
0,01 0,01
0,00 0,00
Execute code online at dotnetfiddle.net
The thousand separator is an issue. Using "n2" will give you 3,543 where using "0.00" will give you 3543. The comma can break down-stream code that might have to parse that value back to a decimal, especially client-side js.
Here is example to explain
int rupees=567.3423;
string rp=rupees.tostring("N2");
--Answer is rp="567.34";
-- N2 gives upto two decimal records.
精彩评论