Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

how can I fix my method of converting Bytes To Megabytes not to get as a Result NaN. This is my method:

   Public Function BytesToMegabytes(bytes As Long) As String
        Dim dblAns As Double = (bytes / 1024) / 1024

        If dblAns = 0 Then
            Return "0"
        End If

        Dim significantFigures = 4
        Dim magnitude = Math.Floor(Math.Log10(dblAns)) 'In this Line I get the NaN
        Dim v As Double = 10 ^ (magnitude - significantFigures + 1)
        dblAns = Math.Floor(dblAns / v) * v

        Dim ci = New CultureInfo("")
        ci.NumberFormat.NumberDecimalSeparator = ","
        ci.NumberFormat.NumberGroupSeparator = "'"

        Return dblAns.ToString("#,##0.###", ci)

    End Function

With Dim usedInklData = BytesToMegabytes(-3271356861) I get the correct result.
and with Dim usedInklData = BytesToMegabytes(-776150324) I get the NaN value.

Please suggest how I could correct this.

Thanks to everyone for their help.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
333 views
Welcome To Ask or Share your Answers For Others

1 Answer

How about you remember if your input is negative and flip the result if it is, after doing the calculation in positive numbers:

Public Function BytesToMegabytes(bytes As Long) As String
    Dim isNeg = bytes < 0
    If isNeg Then bytes *= -1

    Dim dblAns As Double = (bytes / 1024) / 1024

    If dblAns = 0 Then
        Return "0"
    End If

    Dim significantFigures = 4
    Dim magnitude = Math.Floor(Math.Log10(dblAns)) 'In this Line I get the NaN
    Dim v As Double = 10 ^ (magnitude - significantFigures + 1)
    dblAns = Math.Floor(dblAns / v) * v

    Dim ci = New CultureInfo("")
    ci.NumberFormat.NumberDecimalSeparator = ","
    ci.NumberFormat.NumberGroupSeparator = "'"

    If isNeg Then dblAns *= -1

    Return dblAns.ToString("#,##0.###", ci)

End Function

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...