HiveBrain v1.2.0
Get Started
← Back to all entries
patternjavascriptMinor

Integer to English challenge

Submitted by: @import:stackexchange-codereview··
0
Viewed 0 times
englishintegerchallenge

Problem

I have a challenge, which is to create a JavaScript function that turns a given number into the string representation. For example:

console.log(inToEnglish(15)) should print fifteen

console.log(inToEnglish(101)) should print one hundred one

and so on...

This challenge covers Non-Negative, greater than zero Integer numbers.

I have accomplished this objective with the following code:

```
var b4Twenty = ["one", "two", "three", "four", "five", "six", "seven", "eight",
"nine", "ten", "eleven", "twelve", "thirteen", "fourteen", "fifteen", "sixteen",
"seventeen", "eighteen", "nineteen"
];

var b4Hundred = ["twenty", "thirty", "forty", "fifty", "sixty", "seventy",
"eighty", "ninety"
];

function intToEnglish(n) {
return translator(n).trim();
}

function translator(n) {
if( n == 0)
return "";
else if (n <= 19)
return b4Twenty[n - 1] + " ";
else if (n <= 99)
return b4Hundred[Math.floor(n / 10 - 2)] + " " + translator(n % 10);
else if (n <= 199)
return "one hundred " + translator(n % 100);
else if (n <= 999)
return translator(Math.floor(n / 100)) + "hundred " + translator(n % 100);
else if (n <= 1999)
return "one thousand " + translator(n % 1000);
else if (n <= 999999)
return translator(Math.floor(n / 1000)) + "thousand " + translator(n % 1000);
else if (n <= 1999999)
return "one million " + translator(n % 1000000);
else if (n <= 999999999)
return translator(Math.floor(n / 1000000)) + "million " + translator(n % 1000000);
else if (n <= 1999999999)
return "one billion " + translator(n % 1000000000);
else if (n <= 999999999999)
return translator(Math.floor(n / 1000000000)) + "billion " + translator(n % 1000000000);
else if (n <= 1999999999999)
return "one trillion " + translator(n % 1000000000000);
else if(n <= 999999999999999)
return translator(Math.floor(n / 1000000000000)) + "trillion " + t

Solution

intToEnglish(-1) returns "undefined", which might not be what you want. Same goes for fractional values, although I guess that case could be waved... if you only support integers. Even so, you might want to add a check. At the very least, add a comment - problem descriptions are kept separate from your code right now, and that makes it non-obvious that it doesn't support such things!

Negative numbers could be supported via prepending "minus", then translator(Math.abs(n)).

Context

StackExchange Code Review Q#124826, answer score: 3

Revisions (0)

No revisions yet.