.net将小数格式化为两个位置或一个整数

时间:2021-05-31 16:36:22

For 10 I want 10 and not 10.00 For 10.11 I want 10.11

对于10,我想要10,而不是10。11,我想要10。11

Is this possible without code? i.e. by specifying a format string alone simlar to {0:N2}

这可能没有代码吗?即,通过指定格式字符串单独简化为{0:N2}

Thanks!

谢谢!

2 个解决方案

#1


45  

decimal num = 10.11M;

Console.WriteLine( num.ToString( "0.##" ) );

#2


2  

It seems to me that the decimal precision is intrinsic to the decimal type, which defaults to 4 decimal places. If I use the following code:

在我看来,十进制精度是十进制类型的固有属性,它默认为小数点后4位。如果我使用以下代码:

decimal value = 8.3475M;
Console.WriteLine(value);
decimal newValue = decimal.Round(value, 2);
Console.WriteLine(newValue);

The output is:

的输出是:

8.3475
8.35

#1


45  

decimal num = 10.11M;

Console.WriteLine( num.ToString( "0.##" ) );

#2


2  

It seems to me that the decimal precision is intrinsic to the decimal type, which defaults to 4 decimal places. If I use the following code:

在我看来,十进制精度是十进制类型的固有属性,它默认为小数点后4位。如果我使用以下代码:

decimal value = 8.3475M;
Console.WriteLine(value);
decimal newValue = decimal.Round(value, 2);
Console.WriteLine(newValue);

The output is:

的输出是:

8.3475
8.35