Home > database >  vb.net Math.Round drops last 0 in price?
vb.net Math.Round drops last 0 in price?

Time:12-16

I am using a Math.Round function in my program as follows

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

How do i fix this?

CodePudding user response:

you should try using string format, something like this could do what you need:

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

CodePudding user response:

When dealing with money, use Decimal. It will not suffer from precision issues as Double does. 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
Formatted Cost: $4.18
Weight: 0.4056
Weighted Cost: 1.695408
Formatted Weighted Cost: $1.70

Actually, you should probably not use Math.Round here for money. 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. Keep your cost in its original unspoiled numeric format without rounding, and just use C2 format for display only.

  • Related