narasiman rao

narasiman rao

  • NA
  • 519
  • 766.2k

How to convert number in to words using javascript

Sep 6 2012 2:46 AM
How to convert number in to words using javascript

i have following code using javascript.


var th = ['','thousand','million', 'billion','trillion'];

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){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; if (x > 15) return 'too big'; 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,' ');}


Next you link the script into the head of your page using the following code:
<script type="text/javascript" src="toword.js">
</script>

The final step is to call the script to perform the conversion to words for you. To get a number converted to words you just need to call the function passing it the number you want to convert and the corresponding words will be returned.

var words = toWords(num);

i am doing application in asp.net using csharp.
in the  above where to paste the  above code under  source.(in asp.net we have design and source under sourcer where the copy the above code) please help me.


Answers (1)