Skip to content

Instantly share code, notes, and snippets.

@pehrlich
Created March 19, 2012 22:21
Show Gist options
  • Save pehrlich/2127650 to your computer and use it in GitHub Desktop.
Save pehrlich/2127650 to your computer and use it in GitHub Desktop.
JS num2str
// 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);
}
@RichardBronosky
Copy link

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

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment