Skip to content

@pehrlich /number_to_string.js
Created

Embed URL

HTTPS clone URL

Subversion checkout URL

You can clone with
or
.
Download ZIP
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

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
Something went wrong with that request. Please try again.