Created
February 20, 2014 14:21
-
-
Save fusionstrings/9114668 to your computer and use it in GitHub Desktop.
Number to words in Javascript
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
var th = ['','thousand']; | |
var dg = ['zero','one','two','three','four', 'five','six','seven','eight','nine']; | |
var tn = ['ten','eleven','twelve','thirteen', 'fourteen','fifteen','sixteen', 'seventeen','eighteen','nineteen']; | |
var tw = ['twenty','thirty','forty','fifty', 'sixty','seventy','eighty','ninety']; | |
function toWords(s) | |
{ | |
if (s > 1000) return 'too big'; | |
s = s.toString(); | |
s = s.replace(/[\, ]/g,''); | |
if (s != parseFloat(s)) return 'not a number'; | |
var x = s.indexOf('.'); | |
if (x == -1) x = s.length; | |
var n = s.split(''); | |
var str = ''; | |
var sk = 0; | |
for (var i=0; i < x; i++) | |
{ | |
if ((x-i)%3==2) | |
{ | |
if (n[i] == '1') | |
{ | |
str += tn[Number(n[i+1])] + ' '; | |
i++; | |
sk=1; | |
} | |
else if (n[i]!=0) | |
{ | |
str += tw[n[i]-2] + ' '; | |
sk=1; | |
} | |
} | |
else if (n[i]!=0) | |
{ | |
str += dg[n[i]] +' '; | |
if ((x-i)%3==0) str += 'hundred '; | |
sk=1; | |
} | |
if ((x-i)%3==1) | |
{ | |
if (sk) str += th[(x-i-1)/3] + ' '; | |
sk=0; | |
} | |
} | |
if (x != s.length) | |
{ | |
var y = s.length; | |
str += 'point '; | |
for (var i=x+1; i<y; i++) str += dg[n[i]] +' '; | |
} | |
return str.replace(/\s+/g,' '); | |
} | |
toWords(100.09); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment