获取双精度值的小数位数

时间:2014-10-07 09:30:09

标签: .net double scientific-notation

我正在使用VB.NET:

我正在寻找一个获取double值的小数位数的函数。

我已经有一个函数可以为“0.01”这样的值执行此操作,但不会对“1E-6”这样的值执行此操作,但这就是我需要的。

StackOverflow上有一个类似的(已回答)问题,但不适用于科学记数法: Decimal places in a number in VB.NET

所需功能:

Input: 0.001 / Output: 3
Input: 0.000001 (.ToString() representation: "1E-6") / Output: 5

有没有人优雅的方式(VB.NET / C#)?

1 个答案:

答案 0 :(得分:0)

我认为这个功能应该这样做:

    Public Function GetDecimalPlaces(ByVal Value As Double, ByVal Culture As System.Globalization.CultureInfo) As Integer
        Dim val As String = String.Empty
        Dim valSplitted As String() = Nothing

        Try
            val = Value.ToString("0.######################")

            valSplitted = val.Split(CChar(Culture.NumberFormat.NumberDecimalSeparator))
            If (valSplitted.Length = 1) Then Return 0

            Return valSplitted(1).Length
        Catch ex As Exception
            Throw ex
        End Try
    End Function