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?
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)
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With