Tony D Tony D - 5 months ago 21
Vb.net Question

Best way to remove trailing zeros from a Decimal

I have a calculation that returns a decimal with a maximum of two decimal places. What I'd like to achieve is a result that doesn't include decimal zeros, so 8.00 is shown as 8, 8.10 is shown as 8.1 and 8.12 is shown as 8.12.

I've been all over the math functions and can't find anything to achieve this - can anyone point me in the right direction?

Answer

As Benjamin Leinweber pointed out in one of the comments it's probably a product of it being displayed as a string. That said, you could take the duct tape approach and just lop off the trailing digits you don't want like this (who doesn't love duct tape every so often):

    ' Hacky, I did this because Visual Studio removes the 0 in the editor
    Dim num As Decimal = CDec("8.10")

    ' This will now output 8.10
    Console.WriteLine(num)

    ' Put it in a string then trim off the 0's and then the decimal place if it then happens to be at the end
    Dim buf As String = num.ToString
    buf = buf.TrimEnd(New String({"0", "."})) ' trim off the 0's and then the decimal place if it then happens to be at the end at the end

    ' This will output 8.1
    Console.WriteLine(buf)