js function to print words on number

Solutions on MaxInterview for js function to print words on number by the best coders in the world

showing results for - "js function to print words on number"
Isabelle
03 Jan 2020
1// actual  conversion code starts here
2
3var ones = ['', 'one', 'two', 'three', 'four', 'five', 'six', 'seven', 'eight', 'nine'];
4var tens = ['', '', 'twenty', 'thirty', 'forty', 'fifty', 'sixty', 'seventy', 'eighty', 'ninety'];
5var teens = ['ten', 'eleven', 'twelve', 'thirteen', 'fourteen', 'fifteen', 'sixteen', 'seventeen', 'eighteen', 'nineteen'];
6
7function convert_millions(num) {
8  if (num >= 1000000) {
9    return convert_millions(Math.floor(num / 1000000)) + " million " + convert_thousands(num % 1000000);
10  } else {
11    return convert_thousands(num);
12  }
13}
14
15function convert_thousands(num) {
16  if (num >= 1000) {
17    return convert_hundreds(Math.floor(num / 1000)) + " thousand " + convert_hundreds(num % 1000);
18  } else {
19    return convert_hundreds(num);
20  }
21}
22
23function convert_hundreds(num) {
24  if (num > 99) {
25    return ones[Math.floor(num / 100)] + " hundred " + convert_tens(num % 100);
26  } else {
27    return convert_tens(num);
28  }
29}
30
31function convert_tens(num) {
32  if (num < 10) return ones[num];
33  else if (num >= 10 && num < 20) return teens[num - 10];
34  else {
35    return tens[Math.floor(num / 10)] + " " + ones[num % 10];
36  }
37}
38
39function convert(num) {
40  if (num == 0) return "zero";
41  else return convert_millions(num);
42}
43
44//end of conversion code
45
46//testing code begins here
47
48function main() {
49  var cases = [0, 1, 2, 7, 10, 11, 12, 13, 15, 19, 20, 21, 25, 29, 30, 35, 50, 55, 69, 70, 99, 100, 101, 119, 510, 900, 1000, 5001, 5019, 5555, 10000, 11000, 100000, 199001, 1000000, 1111111, 190000009];
50  for (var i = 0; i < cases.length; i++) {
51    console.log(cases[i] + ": " + convert(cases[i]));
52  }
53}
54
55main();
similar questions
queries leading to this page
js function to print words on number