DEV Community

Discussion on: Daily Challenge #19 - Turn numbers into words

Collapse
 
kerrishotts profile image
Kerri Shotts

English is fun what with all the exceptions...

function numToText(n) {
    if (n < 1 || n > 999 || n === undefined) {
        throw new Error(`arg must be > 0 and < 1000`);
    }
    const ones = ["", "one", "two", "three", "four", "five", "six", "seven", "eight", "nine"];
    const prefixes = ["thir", "four", "fif", "six", "seven", "eigh", "nine"];
    const tys = ["", "", "twenty", ...prefixes.map(prefix => `${prefix}ty`)];
    tys[4] = "forty";
    const oneTeens = [...ones, "ten", "eleven", "twelve", ...prefixes.map(prefix => `${prefix}teen`)];

    const parts = [];
    let rem = n;
    if (rem >= 100) {
        parts.push(ones[Math.floor(rem / 100)], "hundred")
        rem = rem % 100;
    }
    if (rem >= 20) {
        parts.push(tys[Math.floor(rem / 10)]);
        rem = rem % 10;
    }
    if (rem > 0 && rem < 20) {
        parts.push(oneTeens[rem]);
    }
    return parts.join(" ");
}
Enter fullscreen mode Exit fullscreen mode

Gist: gist.github.com/kerrishotts/ea2bd9...

Collapse
 
oscherler profile image
Olivier “Ölbaum” Scherler

Try French. I’ll pass you the details of “quatre-vingt-dix-neuf” for 99, but you also have “vingt et un” (21), “vingt deux” (22), “deux cents” (200, note the s) but “deux cent un” (201).