繁体   English   中英

字符串到小数,始终带2个小数位

[英]String to Decimal with 2 decimal places always

我有一个要转换为十进制的字符串。 可以输入的字符串不带小数位,例如“ 123”或2个小数位,例如“ 123.45”或有点尴尬的1个小数位“ 123.3”。 我想要显示2个小数位的数字(Property invoice.Amount ,类型为decimal )。 下面的代码可以做到这一点。 我认为可以写得更好。 怎么样?

decimal newDecimal;
bool isDecimal = Decimal.TryParse(InvoiceDialog.InvoiceAmount, out newDecimal);
string twoDecimalPlaces = newDecimal.ToString("########.00");
invoice.Amount = Convert.ToDecimal(twoDecimalPlaces);

对于字符串格式为“ ########。00”的部分内容,我不了解,#的含义和0的含义。 例如,如果是“ #########。##”,会有什么不同?

#可选数字, 0必填数字

例如

 decimal d = 12.3M;

 // d with exactly 2 digits after decimal point
 Console.WriteLine(d.ToString("########.00"));
 // d with at most 2 digits after decimal point 
 Console.WriteLine(d.ToString("########.##"));

结果:

12.30   // exactly 2 digits after decimal point: fractional part padded by 0
12.3    // at most 2 digits after decimal point: one digit - 3 - is enough

基本上,#表示可选,其中0为必填。 作为更好的解释,如果您输入#,则如果数字可用于填充占位符,则将其添加,否则将被忽略。

但是,将0设为不同,因为它将始终为您输入一个值。

您可以将两者结合在一起。

String.Format("{0:0.##}", 222.222222); // 222.22

String.Format("{0:0.##}", 222.2); // 222.2

String.Format("{0:0.0#}", 222.2) // 222.2

“#”是可选的,而“ 0”将显示数字或0。

例如,

var x = 5.67;
x.ToString("##.###"); // 5.67
x.ToString("00.000"); // 05.670
x.ToString("##.##0"); // 5.670

如果您只是在乎小数位数,建议您使用

x.ToString("f2"); // 5.67

得到2个小数点

可以在http://www.independent-software.com/net-string-formatting-in-csharp-cheat-sheet.html/中找到更多信息。

您无需将decimal转换为string即可格式化2个小数位。 您可以直接使用decimal.Round方法。 你可以在这里阅读。

这样您的代码可以转换为

    decimal newDecimal;
    Decimal.TryParse(s, out newDecimal);

    newDecimal = decimal.Round(newDecimal, 2, MidpointRounding.AwayFromZero);

上面的代码也使用C#7.0声明表达式简化为

    Decimal.TryParse(s, out decimal newDecimal);

    newDecimal = decimal.Round(newDecimal, 2, MidpointRounding.AwayFromZero);

现在newDecimal的值将具有2个精度。

您可以查看现场小提琴。

暂无
暂无

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

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