public
Last active

JS num2str

  • Download Gist
number_to_string.js
JavaScript
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50
// number to string, pluginized from http://stackoverflow.com/questions/5529934/javascript-numbers-to-words
 
window.num2str = function (num) {
return window.num2str.convert(num);
}
 
window.num2str.ones = ['', 'one', 'two', 'three', 'four', 'five', 'six', 'seven', 'eight', 'nine'];
window.num2str.tens = ['', 'one', 'two', 'three', 'four', 'five', 'six', 'seven', 'eight', 'nine'];
window.num2str.teens = ['', 'one', 'two', 'three', 'four', 'five', 'six', 'seven', 'eight', 'nine'];
 
 
window.num2str.convert_millions = function(num) {
if (num >= 1000000) {
return this.convert_millions(Math.floor(num / 1000000)) + " million " + this.convert_thousands(num % 1000000);
}
else {
return this.convert_thousands(num);
}
}
 
window.num2str.convert_thousands = function(num) {
if (num >= 1000) {
return this.convert_hundreds(Math.floor(num / 1000)) + " thousand " + this.convert_hundreds(num % 1000);
}
else {
return this.convert_hundreds(num);
}
}
 
window.num2str.convert_hundreds = function(num) {
if (num > 99) {
return this.ones[Math.floor(num / 100)] + " hundred " + this.convert_tens(num % 100);
}
else {
return this.convert_tens(num);
}
}
 
window.num2str.convert_tens = function(num) {
if (num < 10) return this.ones[num];
else if (num >= 10 && num < 20) return this.teens[num - 10];
else {
return this.tens[Math.floor(num / 10)] + " " + this.ones[num % 10];
}
}
 
window.num2str.convert = function(num) {
if (num == 0) return "zero";
else return this.convert_millions(num);
}

Thanks for creating this. I found that you make a copy pasta mistake in the number string arrays. Please grab lines 7-9 from https://gist.github.com/RichardBronosky/7848621/ab5fa3df8280f718c2e5263a7eabe004790e7e20

Please sign in to comment on this gist.

Something went wrong with that request. Please try again.