我在我的程式中使用 Math.Round 函式如下
Math.Round((ProductWeightByType * 4.18), 2)
這很完美,除了當最后一個字符已經是 0 時,它會去掉那個 0 所以例子 $1.70 變成 $1.7
我該如何解決?
uj5u.com熱心網友回復:
處理金錢時,請使用十進制。它不會像 Double 那樣受到精度問題的影響。哦,不清楚您沒有使用十進制。好吧,您是否不使用字串也不清楚。數字中沒有字符,而是字串。但這是一種使用正確打字的方法
Sub Main()
Dim ProductWeightByType As Decimal = 0.4056D
Dim cost As Decimal = 4.18D
Dim formattedCost As String = $"{cost:C2}"
Dim weightedCost As Decimal = ProductWeightByType * cost
Dim formattedWeightedCost As String = $"{weightedCost:C2}"
Console.WriteLine($"Cost: {cost}")
Console.WriteLine($"Formatted Cost: {formattedCost}")
Console.WriteLine($"Weight: {ProductWeightByType}")
Console.WriteLine($"Weighted Cost: {weightedCost}")
Console.WriteLine($"Formatted Weighted Cost: {formattedWeightedCost}")
Console.ReadLine()
End Sub
成本:4.18
格式化成本:4.18 美元 權
重:0.4056
加權成本:1.695408
格式化加權成本:1.70 美元
實際上,您可能不應該Math.Round在這里賺錢。如果您繼續四舍五入并使用該值,您可能會開始累積幾??分錢的損失或收益。當然,如果你想顯示成本,那么就像其他答案一樣格式化為貨幣(我的也做了兩次)。
請注意,重要的是要說明如何將值$1.695408四舍五入為$1.70,獲得$0.004592。將您的成本保持在原始未受破壞的數字格式中,無需四舍五入,僅使用 C2 格式進行顯示。
uj5u.com熱心網友回復:
你應該嘗試使用string format,這樣的事情可以做你需要的:
String.Format("{0:C2}", Math.Round((ProductWeightByType * 4.18), 2))
轉載請註明出處,本文鏈接:https://www.uj5u.com/qianduan/384925.html
