[英]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.