简体   繁体   English

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

[英]vb.net Math.Round drops last 0 in price?

I am using a Math.Round function in my program as follows我在我的程序中使用 Math.Round function 如下

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

This works perfect except for when the last character is already a 0 then it drops that 0 so example $1.70 becomes $1.7这很完美,除非最后一个字符已经是 0,然后它会丢弃该 0,因此示例 $1.70 变为 $1.7

How do i fix this?我该如何解决?

you should try using string format , something like this could do what you need:您应该尝试使用string format ,这样的事情可以满足您的需要:

String.Format("{0:C2}", Math.Round((ProductWeightByType * 4.18), 2))

When dealing with money, use Decimal.处理金钱时,请使用十进制。 It will not suffer from precision issues as Double does.它不会像 Double 那样遭受精度问题。 Oh, it's not clear that you're not using Decimal.哦,不清楚你没有使用十进制。 Well it's also not clear that your not using strings.好吧,您是否不使用字符串也不清楚。 There are no characters in numbers, rather in strings.数字中没有字符,而是字符串。 But here is an approach which uses proper typing但这是一种使用正确类型的方法

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

Cost: 4.18费用:4.18
Formatted Cost: $4.18格式化成本:4.18 美元
Weight: 0.4056重量:0.4056
Weighted Cost: 1.695408加权成本:1.695408
Formatted Weighted Cost: $1.70格式化加权成本:1.70 美元

Actually, you should probably not use Math.Round here for money.实际上,您可能不应该在这里使用Math.Round来赚钱。 You may start to accumulate a loss or gain of fractions of pennies if you continue to round and use that value.如果您继续四舍五入并使用该值,您可能会开始累积几分之一的损失或收益。 Of course, if you want to display the cost, then format as currency just as the other answer did (mine does it as well twice).当然,如果你想显示成本,那么就像另一个答案一样格式化为货币(我的也是两次)。

Note, it's important to show how if the value is $1.695408 then it is rounded to $1.70 , gaining $0.004592 .请注意,重要的是要说明如果值为$1.695408则将其四舍五入为$1.70 ,获得$0.004592 Keep your cost in its original unspoiled numeric format without rounding, and just use C2 format for display only.将您的成本保持在其原始未损坏的数字格式中,无需四舍五入,并且仅使用 C2 格式进行显示。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM