Home > Back-end >  Formatting a double variable using String Format to add up to 3 zero from the right
Formatting a double variable using String Format to add up to 3 zero from the right

Time:02-19

I got a price decimal which sometimes can be either 0.00002001 or 0.00002. I want to display always 3 zeros from the right if the number is like 0.00002 so I'm looking it to be 0.00002000. If the number is 0.00002001 do not add anything. I came accross some examples and other examplesin msdn and tried with

price.ToString.Format("{0:F4}", price)

but It doesn't actually change anything in the number. And in the case number is like 123456789 I want it to display 123.456.789 which I've half solved using ToString("N2") but it's displaying also a .00 decimals which I don't want.

CodePudding user response:

Some special cases here between the fractional and whole numbers, so they need to be handled differently.

Private Function formatWithTrailingZeros(number As Double) As String
    If number Mod 1 > 0 Then ' has a fractional component
        Return $"{number:0.00000000}"
    Else
        Dim formattedString = $"{number:N2}"
        Return formattedString.Substring(0, formattedString.Length - 3)
    End If
End Function
Dim price = 0.00002001
Console.WriteLine(formatWithTrailingZeros(price))
price = 0.00002
Console.WriteLine(formatWithTrailingZeros(price))
price = 123456789
Console.WriteLine(formatWithTrailingZeros(price))
price = 123456789.012345
Console.WriteLine(formatWithTrailingZeros(price))

0.00002001
0.00002000
123,456,789
123456789.01234500

If your second case with 123.456.789 is not based on your current culture, then you may need to replace , with . such as

Return formattedString.Substring(0, formattedString.Length - 3).Replace(",", ".")

Since you are using . both as a decimal separator and a thousands separator, I'm not sure how my example of 123456789.012345000 should look, but since you didn't ask, I'm not going to guess.

  • Related