Home > Software engineering >  How can I get the whole number without rounding it off?
How can I get the whole number without rounding it off?

Time:11-28

This is the code:

Select Case Math.Truncate(n)
            Case 0
                Return ""

            Case 1 To 19
                Dim arr() As String = {"One", "Two", "Three", "Four", "Five", "Six", "Seven",
                  "Eight", "Nine", "Ten", "Eleven", "Twelve", "Thirteen", "Fourteen",
                    "Fifteen", "Sixteen", "Seventeen", "Eighteen", "Nineteen"}
                Return arr(n - 1) & " "

            Case 20 To 99
                Dim arr() As String = {"Twenty", "Thirty", "Forty", "Fifty", "Sixty", "Seventy", "Eighty", "Ninety"}
                Return arr(n \ 10 - 2) & " " & NumberToText(n Mod 10)

            Case 100 To 199
                Return "One Hundred " & NumberToText(n Mod 100)

            Case 200 To 999
                Return NumberToText(n \ 100) & "Hundred " & NumberToText(n Mod 100)

            Case 1000 To 1999
                Return "One Thousand " & NumberToText(n Mod 1000)

            Case 2000 To 999999
                Return NumberToText(n \ 1000) & "Thousand " & NumberToText(n Mod 1000)

            Case 1000000 To 1999999
                Return "One Million " & NumberToText(n Mod 1000000)

            Case 1000000 To 999999999
                Return NumberToText(n \ 1000000) & "Million " & NumberToText(n Mod 1000000)

            Case 1000000000 To 1999999999
                Return "One Billion " & NumberToText(n Mod 1000000000)

            Case Else
                Return NumberToText(n \ 1000000000) & "Billion " _
                  & NumberToText(n Mod 1000000000)
        End Select

So if the value of **n as Decimal = 98.8**, I should get Ninety-Eight. But instead what I'm getting is Ninety-Nine and my conclusion is it's rounding off. What supposed to be is the problem?

CodePudding user response:

(As @jmcilhinney already suspected in a comment):

You continue to use n (not truncated) under the case statements.
This is easy to debug by stepping through the code.
You'll see the second call with n=8.8, used in arr(n-1), this is an implicit conversion to int, which uses rounding and leads to index 8 (= string Nine).

  • Related