Navigation Menu

Skip to content

Instantly share code, notes, and snippets.

@freewayz
Forked from RichardBronosky/number_to_string.js
Created November 27, 2018 11:25
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save freewayz/2a5442673b1fe6e7ba7567efe8e47c1a to your computer and use it in GitHub Desktop.
Save freewayz/2a5442673b1fe6e7ba7567efe8e47c1a to your computer and use it in GitHub Desktop.
// 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=['','','twenty','thirty','forty','fifty','sixty','seventy','eighty','ninety'];
window.num2str.teens=['ten','eleven','twelve','thirteen','fourteen','fifteen','sixteen','seventeen','eighteen','nineteen'];
window.num2str.convert_millions = function(num) {
var varies = [1000000, " million ", this.convert_thousands]
if (num >= varies[0]) {
return this.convert_millions(Math.floor(num / varies[0])) + varies[1] + varies[2](num % varies[0]);
}
else {
return varies[2](num);
}
}
window.num2str.convert_thousands = function(num) {
var varies = [1000, " thousand ", this.convert_hundreds]
if (num >= varies[0]) {
return this.convert_hundreds(Math.floor(num / varies[0])) + varies[1] + varies[2](num % varies[0]);
}
else {
return varies[2](num);
}
}
window.num2str.convert_hundreds = function(num) {
var varies = [100, " hundred ", this.convert_tens]
if (num >= varies[0]) {
return this.ones[Math.floor(num / varies[0])] + varies[1] + varies[2](num % varies[0]);
}
else {
return varies[2](num);
}
}
window.num2str.convert_tens = function(num) {
var varies = [10, " "]
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);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment