将字符串转换为十进制以始终保留 2 位小数
Convert string to decimal to always have 2 decimal places
我正在尝试将字符串转换为小数,以便始终保留 2 位小数。例如:
- 25.88 -> 25.88
- 25.50 -> 25.50
- 25.00 -> 25.00
但是我在下面的代码中看到了以下内容:
- 25.88 -> 25.88
- 25.50 -> 25.5
- 25.00 -> 25
我的代码:
Decimal.Parse("25.50", CultureInfo.InvariantCulture);
或
Decimal.Parse("25.00");
或
Convert.ToDecimal("25.50");
总之我得到 25.5
。有没有可能不剪掉多余的zeros?
Decimal
有点奇怪,所以,从技术上讲,你 可以 做一点(并且可能是 dirty) 技巧:
// 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
到小数点后的 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
我正在尝试将字符串转换为小数,以便始终保留 2 位小数。例如:
- 25.88 -> 25.88
- 25.50 -> 25.50
- 25.00 -> 25.00
但是我在下面的代码中看到了以下内容:
- 25.88 -> 25.88
- 25.50 -> 25.5
- 25.00 -> 25
我的代码:
Decimal.Parse("25.50", CultureInfo.InvariantCulture);
或
Decimal.Parse("25.00");
或
Convert.ToDecimal("25.50");
总之我得到 25.5
。有没有可能不剪掉多余的zeros?
Decimal
有点奇怪,所以,从技术上讲,你 可以 做一点(并且可能是 dirty) 技巧:
// 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
到小数点后的 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