Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Best way to remove trailing zeros from a Decimal

Tags:

vb.net

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?

like image 850
Tony D Avatar asked Dec 15 '25 07:12

Tony D


2 Answers

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("0")
    buf = buf.TrimEnd(".")

    ' This will output 8.1
    Console.WriteLine(buf)
like image 90
b.pell Avatar answered Dec 16 '25 23:12

b.pell


Are you talking about the VB Decimal data type? If so then read this from the MSDN documentation...

Trailing Zeros. Visual Basic does not store trailing zeros in a Decimal literal. 
However, a Decimal variable preserves any trailing zeros acquired computationally. 
The following example illustrates this. 

Dim d1, d2, d3, d4 As Decimal 

d1 = 2.375D
d2 = 1.625D
d3 = d1 + d2
d4 = 4.000D

MsgBox("d1 = " & CStr(d1) & ", d2 = " & CStr(d2) & 
     ", d3 = " & CStr(d3) & ", d4 = " & CStr(d4))

The output of MsgBox in the preceding example is as follows: 

    d1 = 2.375, d2 = 1.625, d3 = 4.000, d4 = 4

So since the Decimal data type holds on to significant digits in a calculation then you may want to convert the data type to double and use a custom format like {0:#.##} for display

MSDN Decimal Data Type

like image 42
fnostro Avatar answered Dec 16 '25 22:12

fnostro



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!