vb.net Math.Round 价格跌至最后 0?

问题描述 投票:0回答:2

我在程序中使用 Math.Round 函数,如下所示

Math.Round((ProductWeightByType * 4.18), 2)

这很完美,除非最后一个字符已经是 0,然后它会删除 0,例如 $1.70 变成 $1.7

我该如何解决这个问题?

vb.net decimal math.round
2个回答
1
投票

处理金钱时,请使用小数。它不会像 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 格式仅用于显示。


0
投票

你应该尝试使用

string format
,这样的东西可以满足你的需要:

String.Format("{0:C2}", Math.Round((ProductWeightByType * 4.18), 2))
© www.soinside.com 2019 - 2024. All rights reserved.