如何检查VB.NET中数字的小数位数?
例如:在一个循环中我有一个if
语句,在该语句中我想检查一个数字是否有四个小数位(8.9659)。
答案 0 :(得分:5)
Dim numberAsString As String = myNumber.ToString()
Dim indexOfDecimalPoint As Integer = numberAsString.IndexOf(".")
Dim numberOfDecimals As Integer = _
numberAsString.Substring(indexOfDecimalPoint + 1).Length
答案 1 :(得分:4)
考虑整数值的类似方法。
Public Function NumberOfDecimalPlaces(ByVal number As Double) As Integer
Dim numberAsString As String = number.ToString()
Dim indexOfDecimalPoint As Integer = numberAsString.IndexOf(".")
If indexOfDecimalPoint = -1 Then ' No decimal point in number
Return 0
Else
Return numberAsString.Substring(indexOfDecimalPoint + 1).Length
End If
End Function
答案 2 :(得分:2)
Public Shared Function IsInSignificantDigits(val As Double, sigDigits As Integer)
Dim intVal As Double = val * 10 ^ sigDigits
Return intVal = Int(intVal)
End Function
答案 3 :(得分:0)
对于全球化......
Public Function NumberOfDecimalPlaces(ByVal number As Double) As Integer
Dim numberAsString As String = number.ToString(System.Globalization.CultureInfo.InvariantCulture)
Dim indexOfDecimalPoint As Integer = numberAsString.IndexOf(".")
If (indexOfDecimalPoint = -1) Then ' No decimal point in number
Return 0
Else
Return numberAsString.Substring(indexOfDecimalPoint + 1).Length
End If
End Function
答案 4 :(得分:0)
此问题附带的其他一些答案建议将数字转换为字符串,然后使用“点”的字符位置作为小数位数的指示符。但这并不是一种可行的方法。如果数字有多个小数位,则会导致非常不准确的答案,并且它转换为包含指数表示法的字符串。
例如,对于公式1/11111111111111111(一个除以17个),字符串转换为“9E-17”,这意味着当它应为17时得到的答案是5.当然可以提取正确的答案。当“E-”存在时,从字符串末尾回答,但为什么在数学上可以完成呢?
这是我刚刚做的一个功能。这不是一个完美的解决方案,我没有彻底测试过,但似乎有效。
Public Function CountOfDecimalPlaces(ByVal inputNumber As Variant) As Integer
'
' This function returns the count of deciml places in a number using simple math and a loop. The
' input variable is of the Variant data type, so this function is versatile enougfh to work with
' any type of input number.
'
CountOfDecimalPlaces = 0 'assign a default value of zero
inputNumber = VBA.CDec(inputNumber) 'convert to Decimal for more working space
inputNumber = inputNumber - VBA.Fix(inputNumber) 'discard the digits left of the decimal
Do While inputNumber <> VBA.Int(inputNumber) 'when input = Int(input), it's done
CountOfDecimalPlaces = CountOfDecimalPlaces + 1 'do the counting
inputNumber = inputNumber * 10 'move the decimal one place to the right
Loop 'repeat until no decimal places left
End Function
答案 5 :(得分:0)
简单...其中n是位数
Dim n as integer = 2
Dim d as decimal = 100.123456
d = Math.Round(d, n);
MessageBox.Show(d.ToString())
响应:100.12