[英]Convert string to decimal to always have 2 decimal places
我正在尝试将字符串转换为小数以始终保留 2 个小数位。 例如:
但是在我下面的代码中,我看到了以下内容:
我的代码:
Decimal.Parse("25.50", CultureInfo.InvariantCulture);
或
Decimal.Parse("25.00");
或
Convert.ToDecimal("25.50");
对于所有我得到25.5
。 是否有可能不切断多余的零?
Decimal
是一个有点奇怪的类型,所以,从技术上讲,你可以做一些(可能是一个肮脏的)技巧:
// This trick will do for Decimal (but not, say, Double)
// notice "+ 0.00M"
Decimal result = Convert.ToDecimal("25.5", CultureInfo.InvariantCulture) + 0.00M;
// 25.50
Console.Write(result);
但是更好的方法是将Decimal
格式化(表示)为Decimal
后的 2 位数字,只要您想输出它:
Decimal d = Convert.ToDecimal("25.50", CultureInfo.InvariantCulture);
// represent Decimal with 2 digits after decimal point
Console.Write(d.ToString("F2"));
我很惊讶您竟然会遇到这个问题,但是如果您想修复它:
yourNumber.ToString("F2")
即使有更多或更少的小数点,它也会打印到 2 个小数点。
测试:
decimal d1 = decimal.Parse("25.50");
decimal d2 = decimal.Parse("25.23");
decimal d3 = decimal.Parse("25.000");
decimal d4 = Decimal.Parse("25.00");
Console.WriteLine(d1 + " " + d2 + " " + d3.ToString("F2") + " " + d4);
Console.ReadLine();
输出: 25.50 25.23 25.00 25.00
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.