473,408 Members | 2,839 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 473,408 software developers and data experts.

library convert number to string

77
hello...
i have this situation, i want to convert the number format like example "350", become string format "three hundred and fifty"..

Is it anyone who has the library to convert the number like example above..

thanks...
Jul 15 '08 #1
6 4682
dmjpro
2,476 2GB
i think there is no.
you have to make your own function in JS.
I think you are able to do that ..if any problem with writing the code then come here, experts are here.
Jul 15 '08 #2
Hi
Just save the following snippet as js file and call this file in code.

Expand|Select|Wrap|Line Numbers
  1.  
  2. /* Author: Sandesh Karalkar
  3.  * Copyrights: Sandesh Karalkar, 2004
  4.  * SEE: http://in.geocities.com/skexz/
  5.  * ----------------------------------------------------------------------
  6.  * CURRENCY TO WORDS CONVERTOR (Indian version)
  7.  * ----------------------------------------------------------------------
  8.  * Compatible with IE5.5+ and Mozilla 1.0+
  9.  */
  10.  
  11.  
  12. function digitToWordConvertor(number)
  13. {
  14.     try
  15.     {
  16.         var number = getRoundedAmount(number);
  17.         var result = convertCrores(number);
  18.         //dump("\n Number: "+ "["+number+"] " + convertCrores(number));
  19.         return result;
  20.     }
  21.     catch (ex)
  22.     {
  23.         //dump("\n digitToWordConvertor =>" + ex);
  24.     }
  25. }
  26.  
  27.  
  28. function convertCrores(number)
  29. {
  30.     try
  31.     {
  32.         var result;
  33.         if (number <1000000000)
  34.         {
  35.             if (number/10000000 >= 1)
  36.             {
  37.                 result = convertTens(number/10000000) + " Crores";
  38.                 if (number < 100000000)
  39.                 {
  40.                     var crores = String(number)+" ";
  41.                     crores = crores.slice(1,-1);
  42.                     //////dump("\n Thousunds :" + crores);
  43.                     result = result + convertLakhs(crores);
  44.                 }else{
  45.                     var crores = String(number)+" ";
  46.                     crores = crores.slice(2,-1);
  47.                     //////dump("\n Thousunds :" + crores);
  48.                     result = result + convertLakhs(crores);
  49.                 }
  50.             }else{
  51.                 result = convertLakhs(number);
  52.             }
  53.         }else{
  54.             ////dump("\n Number is bigger than 10000000.");
  55.         }
  56.         return String(result);
  57.     }
  58.     catch (ex)
  59.     {
  60.         //dump("\n convertcrores =>" + ex);
  61.     }
  62. }
  63.  
  64.  
  65. function convertLakhs(number)
  66. {
  67.     try
  68.     {
  69.         var result;
  70.         if (number < 10000000)
  71.         {
  72.             if (number/100000 >= 1)
  73.             {
  74.                 result = convertTens(number/100000) + " Lakhs";
  75.                 if (number < 1000000)
  76.                 {
  77.                     var lakhs = String(number)+" ";
  78.                     lakhs = lakhs.slice(1,-1);
  79.                     //////dump("\n Thousunds :" + lakhs);
  80.                     result = result + convertThousund(lakhs);
  81.                 }else{
  82.                     var lakhs = String(number)+" ";
  83.                     lakhs = lakhs.slice(2,-1);
  84.                     //////dump("\n Thousunds :" + lakhs);
  85.                     result = result + convertThousund(lakhs);
  86.                 }
  87.             }else{
  88.                 result = convertThousund(number);
  89.             }
  90.         }
  91.         return String(result);
  92.     }
  93.     catch (ex)
  94.     {
  95.         //dump("\n convertLakhs =>" + ex);
  96.     }
  97. }
  98.  
  99. function convertThousund(number)
  100. {
  101.     try
  102.     {
  103.         var result;
  104.         if (number < 100000)
  105.         {
  106.             if (number/1000 >= 1)
  107.             {
  108.                 result = convertTens(number/1000) + " Thousand";
  109.                 if (number < 10000)
  110.                 {
  111.                     var thousunds = String(number)+" ";
  112.                     thousunds = thousunds.slice(1,-1);
  113.                     //////dump("\n Thousunds :" + thousunds);
  114.                     result = result + convertHundred(thousunds);
  115.                 }else{
  116.                     var thousunds = String(number)+" ";
  117.                     thousunds = thousunds.slice(2,-1);
  118.                     //////dump("\n Thousunds :" + thousunds);
  119.                     result = result + convertHundred(thousunds);
  120.                 }
  121.             }else{
  122.                 result = convertHundred(number);
  123.             }
  124.         }else{
  125.             ////dump("\n Number is bigger than 100000.");
  126.         }
  127.         return String(result);
  128.     }
  129.     catch (ex)
  130.     {
  131.         //dump("\n convertThousund =>" + ex);
  132.     }
  133. }
  134.  
  135.  
  136. function convertHundred(number)
  137. {
  138.     try
  139.     {
  140.         var result;
  141.         if (number < 1000)
  142.         {
  143.             if (number/100 >= 1)
  144.             {
  145.                 result = convertDigit(number/100) + " Hundred";
  146.                 var tens = String(number)+" ";
  147.                 tens = tens.slice(1,-1);
  148.                 result = result + convertTwoDigits(tens);
  149.             }else{
  150.                 result = convertTwoDigits(number);
  151.             }
  152.         }else{
  153.             ////dump("\n Number is bigger than 1000.");
  154.         }
  155.         return result;
  156.     }
  157.     catch (ex)
  158.     {
  159.         //dump("\n convertHundred =>" + ex);
  160.     }
  161. }
  162.  
  163.  
  164. function convertTwoDigits(number)
  165. {
  166.     try
  167.     {
  168.         var result;
  169.         if (number < 100)
  170.         {
  171.             if (number >= 10)
  172.             {
  173.                 result = convertTens(number) + " ";
  174.                 var tens1 = String(number)+" ";
  175.                 tens1 = tens1.slice(3,-1);
  176.                 result = result + convertDecimals(tens1);
  177.             }else{
  178.                 result = convertTens(number) + " ";
  179.                 var tens2 = String(number)+" ";
  180.                 tens2 = tens2.slice(2,-1);
  181.                 result = result + convertDecimals(tens2);
  182.             }
  183.         }else{
  184.             ////dump("\n Number is bigger than 99.");
  185.         }
  186.         return result;
  187.     }
  188.     catch (ex)
  189.     {
  190.         //dump("\n convertTwoDigits =>" + ex);
  191.     }
  192. }
  193.  
  194.  
  195. function convertTens(number)
  196. {
  197.     try
  198.     {
  199.          var convertTensResult;
  200.          if (number < 100)
  201.          {
  202.              if (number >= 10)
  203.              {
  204.                 if (number >= 10 && number <= 19)
  205.                 {
  206.                     if (number >= 10 && number < 11)
  207.                     {
  208.                         convertTensResult = " Ten";
  209.                     }
  210.                     else if (number >= 11 && number < 12)
  211.                     {
  212.                         convertTensResult = " Eleven";
  213.                     }
  214.                     else if (number >= 12 && number < 13)
  215.                     {
  216.                         convertTensResult = " Twelve";
  217.                     }
  218.                     else if (number >= 13 && number < 14)
  219.                     {
  220.                         convertTensResult = " Thirteen";
  221.                     }
  222.                     else if (number >= 14 && number < 15)
  223.                     {
  224.                         convertTensResult = " Fourteen";
  225.                     }
  226.                     else if (number >= 15 && number < 16)
  227.                     {
  228.                         convertTensResult = " Fifteen";
  229.                     }
  230.                     else if (number >= 16 && number < 17)
  231.                     {
  232.                         convertTensResult = " Sixteen";
  233.                     }
  234.                     else if (number >= 17 && number < 18)
  235.                     {
  236.                         convertTensResult = " Seventeen";
  237.                     }
  238.                     else if (number >= 18 && number < 19)
  239.                     {
  240.                         convertTensResult = " Eighteen";
  241.                     }
  242.                     else if (number >= 19 && number < 20)
  243.                     {
  244.                         convertTensResult = " Nineteen";
  245.                     }
  246.                     //////dump("\n convertTensResult: " + convertTensResult);
  247.                 }
  248.                 else
  249.                 {
  250.                     var digitAtTen;
  251.                     digitAtTen = number/10;
  252.  
  253.                     if (digitAtTen >= 2 && digitAtTen < 3)
  254.                     {
  255.                         convertTensResult = " Twenty";
  256.                     }
  257.                     else if (digitAtTen >= 3 && digitAtTen < 4)
  258.                     {
  259.                         convertTensResult = " Thirty";
  260.                     }
  261.                     else if (digitAtTen >= 4 && digitAtTen < 5)
  262.                     {
  263.                         convertTensResult = " Forty";
  264.                     }
  265.                     else if (digitAtTen >= 5 && digitAtTen < 6)
  266.                     {
  267.                         convertTensResult = " Fifty";
  268.                     }
  269.                     else if (digitAtTen >= 6 && digitAtTen < 7)
  270.                     {
  271.                         convertTensResult = " Sixty";
  272.                     }
  273.                     else if (digitAtTen >= 7 && digitAtTen < 8)
  274.                     {
  275.                         convertTensResult = " Seventy";
  276.                     }
  277.                     else if (digitAtTen >= 8 && digitAtTen < 9)
  278.                     {
  279.                         convertTensResult = " Eighty";
  280.                     }
  281.                     else if (digitAtTen >= 9)
  282.                     {
  283.                         convertTensResult = " Ninety";
  284.                     }
  285.                     else if (digitAtTen >= 0)
  286.                     {
  287.                         convertTensResult = ""; 
  288.                     }
  289.                     convertTensResult = convertTensResult +""+ convertDigit(String(number).charAt(1));
  290.                 }
  291.              }else{
  292.                 convertTensResult = convertDigit(number);
  293.              }
  294.          }else{
  295.             ////dump("\n [ERROR:convertTens] The number provided is greater than 100.");
  296.             //convertTensResult = convertDigit(number);
  297.          }
  298.          return convertTensResult;
  299.     }
  300.     catch (ex)
  301.     {
  302.         //dump("\n convertTens =>" + ex);
  303.     }
  304. }
  305.  
  306.  
  307. function convertDigit(number)
  308. {
  309.     try
  310.     {
  311.         var convertDigitResult
  312.             if (number >= 0 && number < 1)
  313.             {
  314.                 convertDigitResult = "";
  315.             }
  316.             else if (number >= 1 && number < 2)
  317.             {
  318.                 convertDigitResult = " One";
  319.             }
  320.             else if (number >= 2 && number < 3)
  321.             {
  322.                 convertDigitResult = " Two";
  323.             }
  324.             else if (number >= 3 && number < 4)
  325.             {
  326.                 convertDigitResult = " Three";
  327.             }
  328.             else if (number >= 4 && number < 5)
  329.             {
  330.                 convertDigitResult = " Four";
  331.             }
  332.             else if (number >= 5 && number < 6)
  333.             {
  334.                 convertDigitResult = " Five";
  335.             }
  336.             else if (number >= 6 && number < 7)
  337.             {
  338.                 convertDigitResult = " Six";
  339.             }
  340.             else if (number >= 7 && number < 8)
  341.             {
  342.                 convertDigitResult = " Seven";
  343.             }
  344.             else if (number >= 8 && number < 9)
  345.             {
  346.                 convertDigitResult = " Eight";
  347.             }
  348.             else if (number >= 9 && number < 20)
  349.             {
  350.                 convertDigitResult = " Nine";
  351.             }
  352.         return convertDigitResult;
  353.     }
  354.     catch (ex)
  355.     {
  356.         //dump("\n convertDigit =>" + ex);
  357.     }
  358. }
  359.  
  360. function convertDecimals(number)
  361. {
  362.     try
  363.     {
  364.         var result;
  365.         if (number != '00')
  366.         {
  367.             ////dump("\n decimals: " + number);
  368.             //result = "Rupees "+ convertTens(number) +" Paisa only";
  369.             result="Rupees Only"
  370.         }else{
  371.             result = "Rupees Only";
  372.         }
  373.         return result;
  374.     }
  375.     catch (ex)
  376.     {
  377.         //dump("\n  =>" + ex);
  378.     }
  379. }
  380.  
  381.  
  382.  
  383. //Convert and round a number to two decimals
  384. function getRoundedAmount(original_number)
  385. {
  386.     var decimals = 2;
  387.     var result1 = original_number * Math.pow(10, decimals)
  388.     var result2 = Math.round(result1)
  389.     var result3 = result2 / Math.pow(10, decimals)
  390.     return pad_with_zeros(result3, decimals)
  391. }
  392. function pad_with_zeros(rounded_value, decimal_places) {
  393.  
  394.     // Convert the number to a string
  395.     var value_string = rounded_value.toString()
  396.  
  397.     // Locate the decimal point
  398.     var decimal_location = value_string.indexOf(".")
  399.  
  400.     // Is there a decimal point?
  401.     if (decimal_location == -1) {
  402.  
  403.         // If no, then all decimal places will be padded with 0s
  404.         decimal_part_length = 0
  405.  
  406.         // If decimal_places is greater than zero, tack on a decimal point
  407.         value_string += decimal_places > 0 ? "." : ""
  408.     }
  409.     else {
  410.  
  411.         // If yes, then only the extra decimal places will be padded with 0s
  412.         decimal_part_length = value_string.length - decimal_location - 1
  413.     }
  414.  
  415.     // Calculate the number of decimal places that need to be padded with 0s
  416.     var pad_total = decimal_places - decimal_part_length
  417.  
  418.     if (pad_total > 0) {
  419.  
  420.         // Pad the string with 0s
  421.         for (var counter = 1; counter <= pad_total; counter++) 
  422.             value_string += "0"
  423.         }
  424.     return value_string
  425. }
  426.  
Jul 15 '08 #3
acoder
16,027 Expert Mod 8TB
You may find this useful.
Jul 15 '08 #4
acoder
16,027 Expert Mod 8TB
Hi
Just save the following snippet as js file and call this file in code.
There's too much repetition and unnecessarily long code which can be cut down in size by some margin.
Jul 15 '08 #5
mrhoo
428 256MB
Ths is another approach- most of the code is for element creation and display, but you can use the 'num' methods with any library-

[HTML]<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN">
<html lang="en">

<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" >


<title> number string test page</title>

<style type="text/css" media="screen">
html,body{background-color:#ffdead}
body{color:black;font-size:125%;font-family:'Times New Roman',serif}
#appDiv{width:75%;max-width:1000px; margin 1em auto}
#numDiv{position:relative;border:5px red ridge;padding:1ex 1em}
button,label, input, textarea{margin-right:5px;font-size:1.1em;font-weight:bold;line-height:1.2}
input,textarea{background:none white;}

button{cursor:pointer}
</style>

<script type="text/javascript">
// in practice, take the script out of the html

(function(){
var di= document.implementation;
if(!di || !di.hasFeature || !di.hasFeature('html','1.0')) return;
window.Run={
emSize: function(){
var who= Run.newElement('span',document.body,'','M',
{fontSize:'1em',padding:'0',position:'absolute',li neHeight:'1',visibility:'hidden'});
var fs= [who.offsetWidth,who.offsetHeight];
document.body.removeChild(who);
return fs;
},
mr: function(hoo){
if(!hoo) return false;
if(typeof hoo== 'string'){
hoo= document.getElementById(hoo);
if (!hoo) return false;
}
var t= hoo.nodeType;
if(t== 11 || t== 1)return hoo;
return false;
},
newElement:function(wot,pa,hoo,txt,sty,attr){
var who=Run.mr(hoo);
pa=Run.mr(pa);
if(who)who.parentNode.removeChild(who);
if(!wot)return;
sty=sty||{};
attr=attr||{};
var el=document.createElement(wot);
if(hoo)el.id=hoo;
for(var p in sty){
el.style[p]=sty[p];
}
for(var p in attr){
try{
el[p]=attr[p];
}
catch(er){
el.setAttribute(p,attr[p]);
}
}
if(txt)el.appendChild(document.createTextNode(txt) );
if(pa)pa.appendChild(el);
return el;
},
numDemo: function(){
var newEl=Run.newElement;
Run.mr('shownumBtn').style.visibility='hidden';
var pa=newEl('div','appDiv','numDiv');
var pa2=newEl('p',pa);
var lab=newEl('label',pa2,'','Number: ');
var inp= newEl('input',lab,'numInp','','',{type:'text',size :'20'});
inp.onchange=function(){
var v=Run.mr('numInp').value;
var v1=v.numWords();
if(v1){
Run.mr('numText').value+='\n'+v+'= '+v1;
}
Run.mr('numInp').value='';
Run.mr('numInp').focus();
}
newEl('button',pa2,'convertBtn','Convert','',{type :'button'});
newEl('button',pa2,'clearnumBtn','Clear','',{type: 'button'});
newEl('button',pa2,'numcloseBtn','Close','',{type: 'button'});
Run.mr('numcloseBtn').onclick= function(){
Run.mr('shownumBtn').style.visibility='visible';
Run.zap('numDiv');
}
Run.mr('clearnumBtn').onclick= function(){
Run.mr('numText').value='';
}
var pa3=newEl('p',pa);
var wh=Run.winSize();
var fs=Run.emSize();
var w=Math.floor(wh[0]/fs[0]);
if(w<20)w=20;
var h=Math.floor(wh[1]/(fs[1]*2));
var el=newEl('textarea',pa3,'numText','','',{cols:w,ro ws:h});
Run.mr(pa).style.width= (el.offsetWidth*1.1)+'px';
},
winSize: function(){
if(window.innerWidth)return [window.innerWidth,window.innerHeight];
var B= document.body;
var D= document.documentElement;
D= (D.clientWidth)? D: B;
return [D.clientWidth,D.clientHeight];
},


numWords: function(s){
s= s ||'';
var yr= false,str= '';
var W= Run.wordstrings;
var d= this.replace(/,/g,'');
var sign= (d.charAt(0)== '-')? 'minus ': '';
if(sign)d= d.substring(1);
var currency=(d.charAt(0)=='$');
if(currency){
d=d.substring(1);
d=parseFloat(d).toFixed(2);
}
if(isNaN(d))return '';
if(parseInt(d,10)>1.0e15){
var X= (+d).toExponential().split(/e/i);
return X[0].numWords()+ ' times ten to the '+
X[1].numWords(' power');
}
var Num= (d).split('.');
var A= Num[0].split('');
var r= Num[1];
var L= A.length;
var ones= L? +A.pop(): 0;
str= W[1][ones];
if(L<= 1) str= str || 'zero';
str= ' '+str;
if(!currency && (W[5] || /^y/i.test(s))){
yr= !r && L== 4 && A[0]== '1';
if(/^y/i.test(s))s= '';
}
if(L > 1){
var tens= +A.pop();
if(tens== 0 && ones>0 && L>2)str= ' and '+str;
else if(tens== 1){
str= ' '+W[2][ones];
}
else{
str= ' '+W[3][tens]+str;
}
if(L>2){
if(L>2){
var Am= W[4].slice(0) ;
var x= Am.shift(),n= 0;
var h= +A.pop();
if(!s && tens && !/^ *and/.test(str)) str=' and '+str;
if(h>0){
if(yr){
if(!tens)str= ' '+x+str;
str= W[2][h]+str.replace(/ and/,'');
return str;
}
else str= ' '+ W[1][h]+x+str;
}
if(L>3){
while(A.length){
n= A.pop();
x= Am.shift();
while(A.length && n.length<3) n= A.pop()+''+n;
if(parseInt(n)){
if(x!= W[4][1] && /\W/.test(str) && !/^ *and/.test(str))str=', '+str;
str= n.numWords(x)+ str;
}
}
}
}
}
}
if(currency){
if(str && !/zero/.test(str)){
str+=' dollar';
if(!/^ *one *dollar/.test(str))str+='s';
}
else str='';
if(r!='00'){
if(str)str+=' and';
str+= r.numWords()+' cents';
}
return sign + (str || 'Zero');
}
if(r){
str= str || 'zero ';
r= r.split('');
r= r.doforAll(function(itm){
return W[1][+itm]+'' || 'zero'
})
return sign +str+' point '+r.join(' ');
}
if(s== ' power'){
str= str.nth();
}
str= str || 'zero';
return sign + str +s;
},

wordstrings:
['English',
['','one','two','three','four','five','six','seven' ,'eight','nine'],
['ten','eleven','twelve','thirteen','fourteen','fif teen','sixteen','seventeen','eighteen','nineteen'],
['','','twenty','thirty','forty','fifty','sixty','s eventy','eighty','ninety'],
[' hundred',' thousand',' million',' billion',' trillion'],
false],
zap:function(who){
who= Run.mr(who);
if(who)who.parentNode.removeChild(who);
}
}
String.prototype.clean= function(){
var str= this.replace(/(^\s+)|(\s+$)/g,'');
return str.replace(/ {2,}/g,' ');
}

String.prototype.nth= function(){
var str= ' '+this.clean();
var L= str.length-1;
if(L && str.charAt(L-1)=='1'){
return str+'th';
}
var suffx= str.charAt(str.length-1);
if(isNaN(suffx)){
if(suffx== 'y') return str.slice(0,-2)+'tieth';
else{
var ax= str.lastIndexOf(' ');
if(ax== -1)ax+= 1;
suffx= str.substring(ax).clean();
if(ax>0)str= str.substring(0,ax);
else str= '';
}
}
switch(suffx){
case 'one': return str+'first';
case '1': return str+'rst';
case 'two':return str+'second';
case '2':return str+'nd';
case 'three': return str+'third';
case '3': return str+'rd';
case 'five': return str+'fifth';
case 'twelve': return str+'twelfth';
default: return str+suffx+'th';
}
}

String.prototype.numWords= Run.numWords;

Number.prototype.numWords= function(n){
if(typeof n== 'number') var s= this.toPrecision(n);
else var s= this+'';
if(n=== 'y') return s.numWords('y');
return s.numWords();
}
Array.prototype.doforAll= function(fun,args){
var L= this.length,A= [], tem;
for(var i= 0; i< L; i++){
try{
if(args)tem= fun.apply(this[i],args);
else tem= fun(this[i]);
}
catch(er){
tem= null;
}
if(tem) A.push(tem);
}
return A;
}
Array.prototype.copy=function(){
var A= [];
var L= this.length;
for(var i= 0;i<L;i++){
A[i]= this[i];
}
return A;
}
window.onload=function(){
var el= Run.newElement('button',document.body,'shownumBtn' ,'Converter','',
{title:'Start number to string converter',onclick:Run.numDemo});
}
})()

</script>


</head>

<body>
<h1>Numbers to words</h1>
<div id="appDiv">
<p>You can use this script to convert any number to (English) words.
If you begin the number with a dollar sign ('$') it will return currency, otherwise,
decimals will be 'spelled out'. Commas in the input will be ignored.</p>
<p><span style="font-weight:bold">Really</span> large numbers are converted to exponential notation.</p>
<p>Converting words to numbers is the next step...</p>

</div>
</body>
</html>
[/HTML]
Jul 15 '08 #6
mrhoo
428 256MB
This is the relevant section of the code in my previous post-

Expand|Select|Wrap|Line Numbers
  1. String.prototype.numWords= function(s){
  2.     s= s || '';
  3.     var yr= false, str= '';
  4.     var W= Number.wordstrings;
  5.     var d= this.replace(/, */g, '');
  6.     var sign=(d.charAt(0)== '-')? 'minus ': '';
  7.     if(sign)d= d.substring(1);
  8.     var currency=(d.charAt(0)=='$');
  9.     if(currency){
  10.         d=d.substring(1);
  11.         d=parseFloat(d).toFixed(2);
  12.     }
  13.     if(isNaN(d))return '';
  14.     if(parseInt(d, 10)>1.0e15){
  15.         var X=(+d).toExponential().split(/e/i);
  16.         return X[0].numWords()+ ' times ten to the '+
  17.         X[1].numWords(' power');
  18.     }
  19.     var Num=(d).split('.');
  20.     var A= Num[0].split('');
  21.     var r= Num[1];
  22.     var L= A.length;
  23.     var ones= L? +A.pop(): 0;
  24.     str= W[1][ones];
  25.     if(L<= 1) str= str || 'zero';
  26.     str= ' '+str;
  27.     if(!currency &&(W[5] || /^y/i.test(s))){
  28.         yr= !r && L== 4 && A[0]== '1';
  29.         if(/^y/i.test(s))s= '';
  30.     }
  31.     if(L > 1){
  32.         var tens= +A.pop();
  33.         if(tens== 0 && ones>0 && L>2)str= ' and '+str;
  34.         else if(tens== 1){
  35.             str= ' '+W[2][ones];
  36.         }
  37.         else{
  38.             str= ' '+W[3][tens]+str;
  39.         }
  40.         if(L>2){
  41.             if(L>2){
  42.                 var Am= W[4].slice(0) ;
  43.                 var x= Am.shift(), n= 0;
  44.                 var h= +A.pop();
  45.                 if(!s && tens && !/^ *and/.test(str)) str=' and '+str;
  46.                 if(h>0){
  47.                     if(yr){
  48.                         if(!tens)str= ' '+x+str;
  49.                         str= W[2][h]+str.replace(/ and/, '');
  50.                         return str;
  51.                     }
  52.                     else str= ' '+ W[1][h]+x+str;
  53.                 }
  54.                 if(L>3){
  55.                     while(A.length){
  56.                         n= A.pop();
  57.                         x= Am.shift();
  58.                         while(A.length && n.length<3){
  59.                             n= A.pop()+''+n;
  60.                         }
  61.                         if(parseInt(n)){
  62.                             if(x!= W[4][1] && /\W/.test(str) &&
  63.                             !/^ *and/.test(str)){
  64.                                 str=', '+str;
  65.                             }
  66.                             str= n.numWords(x)+ str;
  67.                         }
  68.                     }
  69.                 }
  70.             }
  71.         }
  72.     }
  73.     if(currency){
  74.         if(str && !/zero/.test(str)){
  75.             str+=' dollar';
  76.             if(!/^ *one *dollar/.test(str))str+='s';
  77.         }
  78.         else str='';
  79.         if(r!='00'){
  80.             if(str)str+=' and';
  81.             str+= r.numWords()+' cents';
  82.         }
  83.         return sign +(str || 'Zero');
  84.     }
  85.     if(r){
  86.         str= str || 'zero ';
  87.         r= r.split('');
  88.         r= r.doforAll(function(itm){
  89.             return W[1][+itm]+'' || 'zero'
  90.         })
  91.         return sign +str+' point '+r.join(' ');
  92.     }
  93.     if(s== ' power'){
  94.         str= str.nth();
  95.     }
  96.     str= str || 'zero';
  97.     return sign + str +s;
  98. }
  99. Number.wordstrings=
  100. [
  101. 'English',
  102. ['zero', 'one', 'two', 'three', 'four', 'five', 'six',
  103. 'seven' , 'eight', 'nine'],
  104. ['ten', 'eleven', 'twelve', 'thirteen', 'fourteen',
  105. 'fifteen', 'sixteen',
  106. 'seventeen', 'eighteen', 'nineteen'],
  107. ['', '', 'twenty', 'thirty', 'forty', 'fifty', 'sixty',
  108. 'seventy', 'eighty', 'ninety'],
  109. [' hundred', ' thousand', ' million', ' billion', ' trillion'],
  110. false
  111. ]
  112. Number.prototype.numWords= function(n){
  113.     if(typeof n== 'number') var s= this.toPrecision(n);
  114.     else var s= this+'';
  115.     if(n=== 'y') return s.numWords('y');
  116.     return s.numWords();
  117. }
  118. Array.prototype.doforAll= function(fun, args){
  119.     var L= this.length, A= [], tem;
  120.     for(var i= 0; i< L; i++){
  121.         try{
  122.             if(args)tem= fun.apply(this[i], args);
  123.             else tem= fun(this[i]);
  124.         }
  125.         catch(er){
  126.             tem= null;
  127.         }
  128.         if(tem) A.push(tem);
  129.     }
  130.     return A;
  131. }
  132. /* these next methods are for getting the ordinal suffix(first, third, twelfth...) */
  133. String.prototype.clean= function(){
  134.     var str= this.replace(/(^\s+)|(\s+$)/g,'');
  135.     return str.replace(/ {2,}/g,' ');
  136. }
  137. String.prototype.nth= function(){
  138.     var str= ' '+this.clean();
  139.     var L= str.length-1;
  140.     if(L && str.charAt(L-1)=='1'){
  141.         return str+'th';
  142.     }
  143.     var suffx= str.charAt(str.length-1);
  144.     if(isNaN(suffx)){
  145.         if(suffx== 'y') return str.slice(0, -2)+'tieth';
  146.         else{
  147.             var ax= str.lastIndexOf(' ');
  148.             if(ax== -1)ax+= 1;
  149.             suffx= str.substring(ax).clean();
  150.             if(ax>0)str= str.substring(0, ax);
  151.             else str= '';
  152.         }
  153.     }
  154.     switch(suffx){
  155.         case 'one': return str+'first';
  156.         case '1': return str+'rst';
  157.         case 'two':return str+'second';
  158.         case '2':return str+'nd';
  159.         case 'three': return str+'third';
  160.         case '3': return str+'rd';
  161.         case 'five': return str+'fifth';
  162.         case 'twelve': return str+'twelfth';
  163.         default: return str+suffx+'th';
  164.     }
  165. }
  166.  
// test case
var s= '15,278,456,341';
var txt='Type any number of digits(optional decimal point):\nA leading dollar sign($) converts currency.';
while((s= prompt(txt, s)) !=undefined){
txt=s+'= '+s.numWords()+'\n\nAnother?'
}



If you copy this script you can remove the line numbers from the returned string by pasting it in a textarea and running this-

textareareference.value=
textareareference.value.replace(/^\s*(\#?( *\d+) *\.)/gm,'');

Then you can paste the result in a webpage between script tags or just call eval(textareareference.value) to run it from the current window.
Jul 15 '08 #7

Sign in to post your reply or Sign up for a free account.

Similar topics

9
by: Steven T. Hatton | last post by:
I know I can write one, or use QString, etc., but is there a native C++ function to convert a NTBS of digits to an integer? -- "If our hypothesis is about anything and not about some one or more...
7
by: whatluo | last post by:
Hi, all I'm now working on a program which will convert dec number to hex and oct and bin respectively, I've checked the clc but with no luck, so can anybody give me a hit how to make this done...
3
by: Chua Wen Ching | last post by:
I have a problem. But on .NET 1.1 My Scenario: Actually I will have a string of hexadecimals read from a xml file. Then from the hexadecimals, i will add 1 value whenever i made any...
10
by: mwt | last post by:
So in a further attempt to learn some Python, I've taken the little Library program (http://groups.google.com/group/comp.lang.python/browse_thread/thread/f6a9ccf1bc136f84) I wrote and added...
30
by: ceeques | last post by:
Hi I am a novice in C. Could you guys help me solve this problem - I need to convert integer(and /short) to string without using sprintf (I dont have standard libray stdio.h). for...
7
by: elliotng.ee | last post by:
I have a text file that contains a header 32-bit binary. For example, the text file could be: %%This is the input text %%test.txt Date: Tue Dec 26 14:03:35 2006...
1
by: FAQ server | last post by:
----------------------------------------------------------------------- FAQ Topic - Why does 1+1 equal 11? or How do I convert a string to a number?...
0
by: JosAH | last post by:
Greetings, welcome back; above we discussed the peripherals of the Library class: loading and saving such an instantiation of it, the BookMark interface and then some. This part of the article...
2
by: FAQ server | last post by:
----------------------------------------------------------------------- FAQ Topic - Why does 1+1 equal 11? or How do I convert a string to a number?...
0
by: emmanuelkatto | last post by:
Hi All, I am Emmanuel katto from Uganda. I want to ask what challenges you've faced while migrating a website to cloud. Please let me know. Thanks! Emmanuel
0
BarryA
by: BarryA | last post by:
What are the essential steps and strategies outlined in the Data Structures and Algorithms (DSA) roadmap for aspiring data scientists? How can individuals effectively utilize this roadmap to progress...
1
by: nemocccc | last post by:
hello, everyone, I want to develop a software for my android phone for daily needs, any suggestions?
1
by: Sonnysonu | last post by:
This is the data of csv file 1 2 3 1 2 3 1 2 3 1 2 3 2 3 2 3 3 the lengths should be different i have to store the data by column-wise with in the specific length. suppose the i have to...
0
by: Hystou | last post by:
There are some requirements for setting up RAID: 1. The motherboard and BIOS support RAID configuration. 2. The motherboard has 2 or more available SATA protocol SSD/HDD slots (including MSATA, M.2...
0
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However,...
0
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can...
0
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each...
0
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome a new...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.