2021-04-01

Decimal String

You are given numerator and denominator i.e. $N and $D.

Write a script to convert the fraction into decimal string. If the fractional part is recurring then put it in parenthesis.

#!/usr/bin/env tclsh

proc fractionToDecimal {numerator denominator} {
    set n $numerator
    set d $denominator

    if {$n==0} {
        return "0"
    }

    if {($n > 0) ^ ($d > 0)} {
        set solution "-"
    } else {
        set solution ""        
    }

    set n [expr abs($n)]
    set d [expr abs($d)]

    # integral part
    append solution [expr $n / $d]
    set n [expr $n % $d]
    if {$n==0} {
        return $solution
    }

    append solution "."

    # fractional part
    set mymap [dict create $n [string length $solution]]
    while {$n != 0} {
        set n [expr $n * 10]
        set r [expr $n / $d]
        append solution $r
        set n [expr $n % $d]
        if {[dict exists $mymap $n]==1} {
            set index [dict get $mymap $n]
            set result [string range $solution 0 [expr $index-1]]
            append result "("
            append result [string range $solution $index end]
            append result ")"
            set solution $result
            break
        } else {
            dict set mymap $n [string length $solution]
        }
    }

    return $solution
}

if {$argc != 2} {
    exit
}

set n [lindex $argv 0]
set d [lindex $argv 1]
puts [fractionToDecimal $n $d]

沒有留言: