开发者

How should I check if a .NET decimal value is a whole number?

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 wo开发者_如何学Culd 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.


Here's another way

    Public Overrides Function ToString() 
        If (Me.NumericValue - Math.Round(Me.NumericValue, 0) > 0) Then
                Return String.Format("{0:###,###,##0.00}{1}", Me.NumericValue, Units);
        Return String.Format("{0:###,###,##0}{1}", Me.NumericValue, Units)
    End Function


Are you sure you want to do this?

Anyone with an enginerring background will read "7cm" as "approx. seven centimeters" and "7.00cm" as "seven centimetres to the nearest millimeter".

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜