I have class representing a unit of measure with a Decimal
as the numeric. Just to simplify things for this example, let's say I'm representing centimeters. I'd like to implement a ToString() method for this class. The thing is, if the numeric value is a whole number I'd like to just display the decimal as an integer. Otherwise, I'd like to keep it as a decimal. So, for example, 10.5D centimeters would display as "10.5cm", but 7.0D centimeters should display as "7cm". I'd like this to be fast and simple to read. I have a working solution, but it seems like there should be a better way.
Here's a contrived example showing my first crack at it:
Public Property Units As String = "cm"
Public Property NumericValue As Decimal = 10.5D
Public Overrides Function ToString()
Dim num As String = If(Me.NumericValue = Decimal.Ceiling(Me.NumericValue), _
Decimal.ToInt32(Me.NumericValue).ToString(), _
Me.NumericValue.ToString())
Return num + Me.Units
End Function
I'm a little uncomfortable with Me.NumericValue = Decimal.Ceiling(Me.NumericValue)
. Any thoughts on how to do this better? Is there something I could do with String.Format or some other method on the Decimal class that would make this clearer and keep it performant?
You can try:
decimal.Truncate(myDecimal) == myDecimal
This might be good enough for your purposes. However, this a complex issue; simply using System.Decimal
does not get rid of all problems related to floating-point representations. The code-sample here is a case in point.
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