Wednesday, August 12, 2015

english phrase for integer

999,999,999,999 -> nine hundred ninety nine billion, nine hundred ninety nine million, nine hundred ninety nine thousand, nine hundred ninety nine.

Divide the number into groups of 3 digits. Each group has a suffix as thousand, million, billion, etc. except the first. Within the group the phrasing is same.
text(n):
    if n < 0:
        return "negative " + text(-n)
    if n > 999,999,999,999:
        throw
    if n == 0:
        return "zero"
    groups = groupify(n)
    phrase = text(groups)
    return phrase

// create groups of ints 1-999
groupify(n):
    list groups = new
    while n > 0:
        groups.add(n %1000)
        n = n /1000
    return groups

text(groups):
    tokens = new
    for i = groups.count() -1, i >= 0, i--:
        group = groups[i]
        if group > 0:
            grouptokens = new
            grouptokens.add(convert3digits(group))
            groupsuffix = group-suffix(i)
            if groupsuffix != "":
                grouptokens.add(groupsuffix)
            groupphrase = grouptokens.join(" ")
            tokens.add(groupphrase)
    phrase = tokens.join(", ")
    return phrase

// tests
0
1-9
10-19
20,30,...,90
21,32,...,99
100
101-109
110-119
120,130,...,190
121,132,...,199

convert3digits(n):
    if n < 0 || n > 999:
        throw
    tokens = new
    digit3 = n /100
    if digit3 > 0:
        tokens.add(ntophrasemap[digit3])
            .add("hundred")
    digit21 = n %100
    if digit21 > 0:
        if ntophrasemap.has(digit21):
            tokens.add(ntophrasemap[digit21])
        else:
            digit1 = digit21 %10
            digit20 = digit21 - digit1
            tokens.add(ntophrasemap[digit20])
                .add(ntophrasemap[digit1])
    phrase = tokens.join(" ")
    return phrase

group-suffix(i):
    if i == 0:
        return ""
    if i == 1:
        return "thousand"
    if i == 2:
        return "million"
    if i == 3:
        return "billion"
    throw "out of range"

ntophrasemap = build-ntophrasemap()

build-ntophrasemap():
    ntophrasemap = {
    // key -> value
         1 -> "one"
         2 -> "two"
         3 -> "three"
         4 -> "four"
         5 -> "five"
         6 -> "six"
         7 -> "seven"
         8 -> "eight"
         9 -> "nine"
        10 -> "ten"
        11 -> "eleven"
        12 -> "twelve"
        13 -> "thirteen"
        14 -> "fourteen"
        15 -> "fifteen"
        16 -> "sixteen"
        17 -> "seventeen"
        18 -> "eighteen"
        19 -> "nineteen"  
        20 -> "twenty"
        30 -> "thirty"
        40 -> "fourty"
        50 -> "fifty"
        60 -> "sixty"
        70 -> "seventy"
        80 -> "eighty"
        90 -> "ninety"
    }
    return ntophrasemap
[Hat tip to ctci]

No comments:

Post a Comment