Search code examples
mathfractions

Fraction length


How to get the fraction length? If at all possible, without using string operation or loop

should all return length of 3:
5.234
5.23400
5.234000

Any programming language is accepted

[EDIT]

Not a homework, I want to display fractions at its minimum. Example, I defined numeric(18,8) in database. If the user entered only 5.234, the data saved in database is 5.23400000. I just want to display it back as 5.234 only


Solution

  • If Int(num) = num Then Return 0
    num *= 10
    If Int(num) = num Then Return 1
    num *= 10
    If Int(num) = num Then Return 2
    num *= 10
    If Int(num) = num Then Return 3
    num *= 10
    If Int(num) = num Then Return 4
    num *= 10
    If Int(num) = num Then Return 5
    num *= 10
    If Int(num) = num Then Return 6
    num *= 10
    If Int(num) = num Then Return 7
    num *= 10
    If Int(num) = num Then Return 8
    Throw New Exception("Number exceeds expected precision")
    

    No string operations, no loops.

    EDIT:

    BTW, to do this with a loop:

    result = 0
    Do While (Int(num) !> num) 
        num *= 10
        result += 1
    Loop
    Return result
    

    Slightly more elegant