Can anyone give me an easy way to find out the numbers after the decimal point of the double?
All i need to do is to find out if the number ends in 0 like 1.0 or 10.0 or 32
If your input is a string, and you want to identify strings that have decimals, but where those decimal places are all zero, then you could use a regular expression:
var regex = new Regex("^-?\\d+\\.0+$");
if (new Regex.IsMatch(input))
{
// it's in the format you want
}
It's been a while, nevertheless my solution:
I also used the mod function, but you have to be careful with that as there are precision "problems" with the data type 'Double':
Dim numberDbl As Double = 1.2
Dim modValDbl As Double = 1.0
Dim remValDbl As Double = numberDbl Mod modValDbl
'remValDbl = 0.19999999999999996 -> not 100% precise
Dim numberDec As Decimal = 1.2D
Dim modValDec As Decimal = 1D
Dim remValDec As Decimal = numberDec Mod modValDec
'remValDec = 0.2 -> correct
Therefore I wrote this function: (example: number = 1.25)
as soon the two values match (i.e.: 25 = 25) I can return my decimal value using remVal and multiplier
Public Shared Function getDecimalPlaces(number As Double) As Double
Dim modVal As Integer = CInt(If(Math.Truncate(number) = 0, 1, Math.Truncate(number)))
Dim remVal As Decimal = CDec(number) Mod modVal
Dim retVal As Double = 0
Debug.WriteLine("modVal: " + modVal.ToString)
Debug.WriteLine("remVal: " + remVal.ToString)
Dim multiplier As Decimal = 1
While remVal * multiplier <> Math.Truncate(remVal * multiplier)
Debug.WriteLine("remVal * multiplier <> Math.Truncate(remVal * multiplier): " + (remVal * multiplier).ToString + " <> " + (Math.Truncate(remVal * multiplier)).ToString)
multiplier *= 10
Debug.WriteLine("remVal * multiplier <> Math.Truncate(remVal * multiplier): " + (remVal * multiplier).ToString + " <> " + (Math.Truncate(remVal * multiplier)).ToString)
End While
retVal = CDbl(remVal * multiplier)
Debug.WriteLine("remVal: " + remVal.ToString)
Debug.WriteLine("multiplier: " + multiplier.ToString)
Debug.WriteLine("retVal: " + retVal.ToString)
Return retVal
End Function
'Output with number = 1.25
'modVal: 1
'remVal: 0,25
'remVal * multiplier <> Math.Truncate(remVal * multiplier): 0,25 <> 0 -> true
'remVal * multiplier <> Math.Truncate(remVal * multiplier): 2,50 <> 2 -> true
'remVal * multiplier <> Math.Truncate(remVal * multiplier): 2,50 <> 2 -> true
'remVal * multiplier <> Math.Truncate(remVal * multiplier): 25,00 <> 25 -> false: exit while
'remVal: 0,25
'multiplier: 100
'retVal: 25