简体   繁体   English

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

[英]Format decimal to two places or a whole number

For 10 I want 10 and not 10.00 For 10.11 I want 10.11 对于10我想要10而不是10.00对于10.11我想要10.11

Is this possible without code? 这可能没有代码吗? ie by specifying a format string alone simlar to {0:N2} 即通过单独指定格式字符串{0:N2}

decimal num = 10.11M;

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

It seems to me that the decimal precision is intrinsic to the decimal type, which defaults to 4 decimal places. 在我看来,十进制精度是十进制类型固有的,默认为4位小数。 If I use the following code: 如果我使用以下代码:

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

The output is: 输出是:

8.3475
8.35

This can be achieved using CultureInfo. 这可以使用CultureInfo实现。 Use the below using statement to import the library. 使用以下using语句导入库。

using System.Globalization;

For the decimal conversion, ## can be used for optional decimal places and 00 can be used for mandetory decimal places. 对于十进制转换,##可用于可选的小数位,00可用于管理小数位。 Check the below examples 请查看以下示例

double d1 = 12.12;
Console.WriteLine("Double :" + d1.ToString("#,##0.##", new CultureInfo("en-US")));

String str= "12.09";
Console.WriteLine("String :" + Convert.ToDouble(str).ToString("#,##0.00", new CultureInfo("en-US")));

String str2 = "12.10";
Console.WriteLine("String2 with ## :" + Convert.ToDouble(str2).ToString("#,##0.##", new CultureInfo("en-US")));
Console.WriteLine("String2 with 00 :" + Convert.ToDouble(str2).ToString("#,##0.00", new CultureInfo("en-US")));


int integ = 2;
Console.WriteLine("Integer :" + Convert.ToDouble(integ).ToString("#,##0.00", new CultureInfo("en-US")));

the results are as follows 结果如下

Double :12.12
String :12.09
String2 with ## :12.1
String2 with 00 :12.10
Integer :2.00

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

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