SitePoint Sponsor

User Tag List

Page 1 of 2 12 LastLast
Results 1 to 25 of 34
  1. #1
    SitePoint Member
    Join Date
    Dec 2007
    Posts
    23
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)

    convert money to words (was "Can anyone Help Me Please (:@)")

    Hi everyone

    I wonder if any one can help me, I've been searching the net for a javascript script, which when you type in any figure it will return that figure in written words.

    For example: 200.10 returns two hundred dollars and ten cents,

    and : 1.1 = one dollar and one cent (note single and plural dollar/dollars and cent/cents)

    I've found scripts in PHP & VB but as I know less about these then javascript, can I convert these to javascript (easy) ?

    I don't know where to start, I'm not that great with javascript but could modify and change a working script to fit my bill.


    Many Thanks for any help.

    Steve

  2. #2
    Unobtrusively zen silver trophybronze trophy
    paul_wilkins's Avatar
    Join Date
    Jan 2007
    Location
    Christchurch, New Zealand
    Posts
    14,527
    Mentioned
    84 Post(s)
    Tagged
    4 Thread(s)

  3. #3
    SitePoint Member
    Join Date
    Dec 2007
    Posts
    23
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    Thanks but this don't have Pounds & Pence or Dollars & Cents, I've tried to add them but without success.

    anymore scripts out there..............

    Steve.

  4. #4
    Unobtrusively zen silver trophybronze trophy
    paul_wilkins's Avatar
    Join Date
    Jan 2007
    Location
    Christchurch, New Zealand
    Posts
    14,527
    Mentioned
    84 Post(s)
    Tagged
    4 Thread(s)
    The other scripts you've found will be easy to convert to javascript

  5. #5
    SitePoint Member
    Join Date
    Dec 2007
    Posts
    23
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    Hi
    when you say its possible to convert PHP to javascript How ?
    manually or is their a programme that will do it automatically,
    Beggars can't be choosers but I don't hold a lot of faith in auto coders, I play around with HTML and have two editors one do it all no coding experience needed Jobie and the other a basic editor, and the extra code put in by the auto coding editor is mad and some what confusing,
    anyway here is the code in PHP any pointers as to how one converts it to good old JS would be much welcomed:

    Code:
    <?php
    
    //*************************************************************
    // this function converts an amount into alpha words
    // and adds the words dollars and cents.  Pass it a float.
    // works up to 999,999,999.99 dollars - send me a check
    //*************************************************************
    
    function makewords($numval)
    {
    $moneystr = "";
    // handle the millions
    $milval = (integer)($numval / 1000000);
    if($milval > 0)
      {
      $moneystr = getwords($milval) . " Million";
      }
    
    // handle the thousands
    $workval = $numval - ($milval * 1000000); // get rid of millions
    $thouval = (integer)($workval / 1000);
    if($thouval > 0)
      {
      $workword = getwords($thouval);
      if ($moneystr == "")
        {
        $moneystr = $workword . " Thousand";
        }
      else
        {
        $moneystr .= " " . $workword . " Thousand";
        }
      }
    
    // handle all the rest of the dollars
    $workval = $workval - ($thouval * 1000); // get rid of thousands
    $tensval = (integer)($workval);
    if ($moneystr == "")
      {
      if ($tensval > 0)
        {
        $moneystr = getwords($tensval);
        }
      else
        {
        $moneystr = "Zero";
        }
      }
    else // non zero values in hundreds and up
      {
      $workword = getwords($tensval);
      $moneystr .= " " . $workword;
      }
    
    // plural or singular 'dollar'
    $workval = (integer)($numval);
    if ($workval == 1)
      {
      $moneystr .= " Dollar And ";
      }
    else
      {
      $moneystr .= " Dollars And ";
      }
    
    // do the pennies - use printf so that we get the
    // same rounding as printf
    $workstr = sprintf("&#37;3.2f",$numval); // convert to a string
    $intstr = substr($workstr,strlen - 2, 2);
    $workint = (integer)($intstr);
    if ($workint == 0)
      {
      $moneystr .= "Zero";
      }
    else
      {
      $moneystr .= getwords($workint);
      }
    if ($workint == 1)
      {
      $moneystr .= " Cent";
      }
    else
      {
      $moneystr .= " Cents";
      }
    
    // done - let's get out of here!
    return $moneystr;
    }
    
    //*************************************************************
    // this function creates word phrases in the range of 1 to 999.
    // pass it an integer value
    //*************************************************************
    function getwords($workval)
    {
    $numwords = array(
      1 => "One",
      2 => "Two",
      3 => "Three",
      4 => "Four",
      5 => "Five",
      6 => "Six",
      7 => "Seven",
      8 => "Eight",
      9 => "Nine",
      10 => "Ten",
      11 => "Eleven",
      12 => "Twelve",
      13 => "Thirteen",
      14 => "Fourteen",
      15 => "Fifteen",
      16 => "Sixteen",
      17 => "Seventeen",
      18 => "Eightteen",
      19 => "Nineteen",
      20 => "Twenty",
      30 => "Thirty",
      40 => "Forty",
      50 => "Fifty",
      60 => "Sixty",
      70 => "Seventy",
      80 => "Eighty",
      90 => "Ninety");
    
    // handle the 100's
    $retstr = "";
    $hundval = (integer)($workval / 100);
    if ($hundval > 0)
      {
      $retstr = $numwords[$hundval] . " Hundred";
      }
    
    // handle units and teens
    $workstr = "";
    $tensval = $workval - ($hundval * 100); // dump the 100's
    if (($tensval < 20) && ($tensval > 0))// do the teens
      {
      $workstr = $numwords[$tensval];
      }
    else // got to break out the units and tens
      {
      $tempval = ((integer)($tensval / 10)) * 10; // dump the units
      $workstr = $numwords[$tempval]; // get the tens
      $unitval = $tensval - $tempval; // get the unit value
      if ($unitval > 0)
        {
        $workstr .= " " . $numwords[$unitval];
        }
      }
    
    // join all the parts together and leave
    if ($workstr != "")
      {
      if ($retstr != "")
        {
        $retstr .= " " . $workstr;
        }
      else
        {
        $retstr = $workstr;
        }
      }
    return $retstr;
    }
    
    
    $floatval = 1.02;
    $myresult = makewords($floatval);
    echo "$myresult<br>";
    printf("The value is %0.2f<br>",$floatval);
    
    
    ?>
    Many thanks

    Steve.

  6. #6
    SitePoint Author silver trophybronze trophy

    Join Date
    Nov 2004
    Location
    Ankh-Morpork
    Posts
    12,159
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    Here's something that should be close to what you want, although "1.1" will be translated as "one dollar and ten cents". If you want "one dollar and one cent" you need to specify the value as "1.01".

    I've not tested very thoroughly, so there may be some bugs.
    Code JavaScript:
    function spellOut(amount) {
    	var exp = ["", "thousand", "million", "billion", "trillion"];
    	var dec = ["", "", "twenty", "thirty", "forty", "fifty", "sixty", "seventy", "eighty", "ninety"];
    	var sing = ["", "one", "two", "three", "four", "five", "six", "seven", "eight", "nine", "ten",
    		        "eleven", "twelve", "thirteen", "fourteen", "fifteen", "sixteen", "seventeen", "eighteen", "nineteen"];
     
    	// Round to two decimal points and format as a string
    	var str = parseFloat(amount).toFixed(2);
     
    	// Extract the integer part and the fraction part
    	var intStr = str.substring(0, str.length - 3);
    	var frac = str.substring(str.length - 2);
     
    	// Compute the number of three-digit groups
    	var tot = "";
    	var len = intStr.length;
    	var grp = Math.floor(len / 3) + (len &#37; 3 == 0 ? 0 : 1);
     
    	// For each group ...
    	for (var g = grp; g > 0; --g) {
    		var p = len - 3 * g;
    		var s = "";
     
    		// Format the hundreds
    		if (p >= 0 && intStr[p] != '0') {
    			s += sing[parseInt(intStr[p])] + " hundred";
    		}
     
    		// Format values between 1 and 99
    		if (p >= -1) {
    			if (intStr[p + 1] < '2') {
    				if (s != "") s += " ";
    				s += sing[10 * parseInt(intStr[p + 1]) + parseInt(intStr[p + 2])];
    			} else {
    				if (s != "") s += " ";
    				s += dec[parseInt(intStr[p + 1])];
    				if (intStr[p + 2] > '0') {
    					s += '-' + sing[parseInt(intStr[p + 2])];
    				}
    			}
     
    		// Special case if amount < 10
    		} else if (intStr[p + 2] > '0') {
    			if (s != "") s += " ";
    			s += sing[parseInt(intStr[p + 2])];
    		}
     
    		// Add exponent descriptor
    		if (s != "") {
    			var e = exp[g - 1];
    			if (e != "") {
    				s += " " + e;
    			}
    		}
     
    		// Append to total string
    		if (tot != "") tot += " ";
    		tot += s;
    	}
     
    	// Append "dollar(s)"
    	var d = parseInt(intStr);
    	if (d == 1) {
    		tot += " dollar";
    	} else if (d > 1) {
    		tot += " dollars";
    	}
     
    	// Append fractional part, if not zero
    	if (frac != "00") {
    		if (tot != "") tot += " and ";
    		var c = "";
    		if (frac[0] < '2') {
    			c = sing[10 * parseInt(frac[0]) + parseInt(frac[1])];
    		} else {
    			c = dec[parseInt(frac[0])];
    			if (frac[1] > '0') {
    				c += '-' + sing[parseInt(frac[1])];
    			}
    		}
    		tot += c + (frac == "01" ? " cent" : " cents");
    	}
     
    	// Special case if amount == 0
    	if (tot == "") tot = "zero";
     
    	return tot;
    }
    Birnam wood is come to Dunsinane

  7. #7
    Unobtrusively zen silver trophybronze trophy
    paul_wilkins's Avatar
    Join Date
    Jan 2007
    Location
    Christchurch, New Zealand
    Posts
    14,527
    Mentioned
    84 Post(s)
    Tagged
    4 Thread(s)
    Here is the javascript version that I have converted from the php code.
    All code paths have been tested, and the test values work fine.

    The only conversion that I haven't bothered with is sprintf, for which I've included a javascript sprintf wrapper for it instead.

    Code HTML4Strict:
    <script type="text/javascript" src="js/webtoolkit.sprintf.js"></script>

    Code JavaScript:
    //*************************************************************
    // this function converts an amount into alpha words
    // and adds the words dollars and cents.  Pass it a float.
    // works up to 999,999,999.99 dollars - send me a check
    //*************************************************************
     
    function makewords(numval)
    {
      var moneystr = '';
      var workword;
      var workval, milval,  thouval, dollarval;
      // handle the millions
      milval = parseInt(numval / 1000000);
      if(milval > 0)
      {
        moneystr = getwords(milval) + ' Million';
      }
     
      // handle the thousands
      workval = numval - (milval * 1000000); // get rid of millions
      thouval = parseInt(workval / 1000);
      if(thouval > 0)
      {
        workword = getwords(thouval);
        if (moneystr == '')
        {
          moneystr = workword + ' Thousand';
        }
        else
        {
          moneystr += ' ' + workword + ' Thousand';
        }
      }
     
      // handle all the rest of the dollars
      workval = workval - (thouval * 1000); // get rid of thousands
      dollarval = parseInt(workval);
      if (moneystr == '')
      {
        if (dollarval > 0)
        {
          moneystr = getwords(dollarval);
        }
        else
        {
          moneystr = 'Zero';
        }
      }
      else // non zero values in hundreds and up
      {
        workword = getwords(dollarval);
        moneystr += ' ' + workword;
    	console.log(dollarval);
      }
     
      // plural or singular 'dollar'
      workval = parseInt(numval);
      if (workval == 1)
      {
        moneystr += ' Dollar And ';
      }
      else
      {
        moneystr += ' Dollars And ';
      }
     
      // do the pennies - use printf so that we get the
      // same rounding as printf
      workstr = sprintf('%3.2f', numval); // convert to a string
      intstr = workstr.substr(workstr.length - 2, 2);
      workint = parseInt(intstr);
      if (workint == 0)
      {
        moneystr += 'Zero';
      }
      else
      {
        moneystr += getwords(workint);
      }
      if (workint == 1)
      {
        moneystr += ' Cent';
      }
      else
      {
        moneystr += ' Cents';
      }
     
      // done - let's get out of here!
      return moneystr;
    }
     
    //*************************************************************
    // this function creates word phrases in the range of 1 to 999.
    // pass it an integer value
    //*************************************************************
    function getwords(workval)
    {
      var numwords = [
        '',
        'One',
        'Two',
        'Three',
        'Four',
        'Five',
        'Six',
        'Seven',
        'Eight',
        'Nine',
        'Ten',
        'Eleven',
        'Twelve',
        'Thirteen',
        'Fourteen',
        'Fifteen',
        'Sixteen',
        'Seventeen',
        'Eightteen',
        'Nineteen',
        'Twenty'
      ];
        numwords[30] = 'Thirty';
        numwords[40] = 'Forty';
        numwords[50] = 'Fifty';
        numwords[60] = 'Sixty';
        numwords[70] = 'Seventy';
        numwords[80] = 'Eighty';
        numwords[90] = 'Ninety';
     
      // handle the 100's
      var retstr = '';
      var hundval = parseInt(workval / 100);
      if (hundval > 0)
      {
        retstr = numwords[hundval] + ' Hundred';
      }
     
      // handle units and teens
      var workstr = '';
      var tensval = workval - (hundval * 100); // dump the 100's
      if ((tensval < 20) && (tensval > 0))// do the teens
      {
        workstr = numwords[tensval];
      }
      else // got to break out the units and tens
      {
        tempval = parseInt(tensval / 10) * 10; // dump the units
        workstr = numwords[tempval]; // get the tens
        unitval = tensval - tempval; // get the unit value
        if (unitval > 0)
        {
          workstr += ' ' + numwords[unitval];
        }
      }
     
      // join all the parts together and leave
      if (workstr != '')
      {
        if (retstr != '')
        {
          retstr += ' ' + workstr;
        }
        else
        {
          retstr = workstr;
        }
      }
      return retstr;
    }
     
    floatval = 1.02;
    myresult = makewords(floatval);
    document.write(myresult + '<br>');
    document.write(sprintf('The value is %0.2f<br>', floatval) + '<br>');
     
    floatval = 1111.01;
    myresult = makewords(floatval);
    document.write(myresult + '<br>');
    document.write(sprintf('The value is %0.2f<br>', floatval) + '<br>');
     
    floatval = 1001111.01;
    myresult = makewords(floatval);
    document.write(myresult + '<br>');
    document.write(sprintf('The value is %0.2f<br>', floatval) + '<br>');
     
    floatval = 0;
    myresult = makewords(floatval);
    document.write(myresult + '<br>');
    document.write(sprintf('The value is %0.2f<br>', floatval) + '<br>');

  8. #8
    SitePoint Enthusiast
    Join Date
    Dec 2007
    Posts
    66
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    Here's another version. I tried to put my code into its own namespace to keep from messing in the global space. It's not polished, but I think it works.

    Code:
    var MoneyConverter = function() {
        var num = [" zero", " one", " two", " three", " four", " five", " six", " seven", " eight", " nine"];
        var teens = [" ten", " eleven", " twelve", " thirteen", " fourteen", " fifteen", " sixteen", " seventeen", " eighteen", " nineteen"];
        var tennums = [" twenty", " thirty", " forty", " fifty", " sixty", " seventy", " eighty", " ninety"];
        return {
            /**
             * Convert a decimal value to textual dollar and cents
             * @param {Float} amt The decimal value
             * @return The textual dollar and cents value
             */
            toTextDollars : function(amt) {
                if (amt > 999999999.99 || amt < 0) {
                    return "invalid amount";
                }
                var decimal = amt - Math.floor(amt);
                return this.toTextualValue(amt) + " dollars " + this.decimalTextualValue(decimal);
            }, 
            toTextualValue : function(amt) {
                if (amt == 0) {
                    return "zero";
                }            
                
                var result = "";
                var millions = Math.floor(amt / 1000000);
                var m = millions * 1000000;
                var thousands = Math.floor((amt - m) / 1000);
                var th = thousands * 1000;
                var hundreds = Math.floor((amt - (m + th)) / 100);
                var h = hundreds * 100;
                var tens = Math.floor((amt - (m + th + h)) / 10);
                var t = tens * 10;
                var ones = Math.floor((amt - (m + th + h + t)));
                
                if (millions >= 1) {
                    result += this.toTextualValue(millions) + " million";
                }
                if (thousands >= 1) {
                    result += this.toTextualValue(thousands) + " thousand";
                }
                if (hundreds >= 1) {
                    result += this.toTextualValue(hundreds) + " hundred";
                }
                if (tens > 0) {
                    if (tens == 1) {
                        result += teens[ones];
                    }
                    else {
                        result += tennums[tens - 2];
                    } 
                }
                if (ones > 0 && tens != 1) {
                    result += num[ones];
                }
                 
                return result;
            },
            decimalTextualValue : function(d) { // 1 - 99
                var dint = d * 100;
                if (dint > 0) {
                    return " and " + this.toTextualValue(dint) + " cents";
                }
                else {
                    return "";
                }
            }
        };
    }();
    
    alert(MoneyConverter.toTextDollars(125222121.4));

  9. #9
    SitePoint Guru
    Join Date
    Apr 2006
    Posts
    802
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    I guess we all have our favorites- here's a cut and paste page I like.
    Code:
    <!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&#37;;font-family:'Times New Roman',serif}
    #numDiv{position:relative;border:5px red ridge;padding:1ex 1em}
    button,label, input, textarea{margin-right:1em;font-size:1.1em;font-weight:bold;line-height:1.2}
    input,textarea{background:none white}
    p{width:600px;font-weight:500}
    button{cursor:pointer}
    </style>
    
    <script type="text/javascript">
    // in practice, take the script out of the html
    
    (function(){
    	if(typeof Run!= 'object') Run={};
    	if(Run.numWords)return true;	
    	var di= document.implementation;
    	if(!di || !di.hasFeature || !di.hasFeature('html','1.0'))return;
    	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';
    		}
    	}
    
    	Run.wordstrings=
    	['English',
    	['','one','two','three','four','five','six','seven','eight','nine'],
    	['ten','eleven','twelve','thirteen','fourteen','fifteen','sixteen','seventeen','eighteen','nineteen'],
    	['','','twenty','thirty','forty','fifty','sixty','seventy','eighty','ninety'],
    	[' hundred',' thousand',' million',' billion',' trillion'],
    	false]
    	Run.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].copy() ;
    					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;
    	}
    	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;
    	}
    	String.prototype.clean= function(){
    		var str= this.replace(/(^\s+)|(\s+$)/g,'');
    		return str.replace(/ {2,}/g,' ');
    	}
    	Array.prototype.copy=function(){
    			var A= [];
    			var L= this.length;
    			for(var i= 0;i<L;i++){
    				A[i]= this[i];
    			}
    			return A;
    		}
    	
    	Run.emSize= function(){		
    		var who= Run.newElement('span',document.body,'','M',
    		{fontSize:'1em',padding:'0',position:'absolute',lineHeight:'1',visibility:'hidden'});
    		var fs= [who.offsetWidth,who.offsetHeight];
    		document.body.removeChild(who);
    		return fs;
    	}
    	Run.newElement=function(wot,pa,hoo,txt,sty,attr){
    		var who=mr(hoo);
    		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(mr(pa))mr(pa).appendChild(el);
    		return el;
    	}
    	Run.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];
    	}
    
    	Run.numDemo= function(){
    		var newEl=Run.newElement;
    		mr('shownumBtn').style.visibility='hidden';
    		var pa=newEl('div',document.body,'numDiv');
    		var pa2=newEl('p',pa);
    		var lab=newEl('label',pa2,'','Type a number and press "Enter":');
    		var inp= newEl('input',lab,'numInp','','',{type:'text',size:'20'});
    		inp.onchange=function(){
    			var v=mr('numInp').value;
    			var v1=v.numWords();
    			if(v1){
    				mr('numText').value+='\n'+v+'= '+v1;			
    			}
    			mr('numInp').value='';
    			mr('numInp').focus();
    		}
    		newEl('button',pa2,'clearnumBtn','Clear','',{type:'button'});			
    		newEl('button',pa2,'numcloseBtn','Close','',{type:'button'});
    		mr('numcloseBtn').onclick= function(){
    			mr('shownumBtn').style.visibility='visible';
    			document.body.removeChild(mr('numDiv'))
    		}
    		mr('clearnumBtn').onclick= function(){
    			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,rows:h});
    		mr(pa).style.width= (el.offsetWidth*1.1)+'px';			
    	}
    	window.mr= function mr(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;
    	}
    	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</h2>
    <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 a number value is the next step...</p>
    </body>
    </html>
    Last edited by mrhoo; Dec 19, 2007 at 03:08.

  10. #10
    SitePoint Member
    Join Date
    Dec 2007
    Posts
    23
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    Hi Guys

    What can I say, I'm like a kid in toy shop,
    Loads of scripts to play and mess about with, I haven't yet tried them but will do straight after this message,
    I would just like to say a big public thanks to:

    AutisticCuckoo, pmw57, Fotiman, mrhoo

    For taking the time and effort to help me out, Cheers chaps

    Steve.

  11. #11
    SitePoint Member
    Join Date
    Dec 2007
    Posts
    23
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    Hi Chaps

    Sorry to be a pain in the Ar$ but I can't get anything working (probably me)

    AutisticCuckoo:
    Can you help what am I doing wrong here, not getting any results back !

    Code:
    <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
        "http://www.w3.org/TR/html4/loose.dtd">
    
    <html>
    
    <head>
      <title></title>
    </head>
    
    <body>
    
    
    <script type="text/javascript">
    
    function spellOut(amount) {
        var exp = ["", "thousand", "million", "billion", "trillion"];
        var dec = ["", "", "twenty", "thirty", "forty", "fifty", "sixty", "seventy", "eighty", "ninety"];
        var sing = ["", "one", "two", "three", "four", "five", "six", "seven", "eight", "nine", "ten",
                    "eleven", "twelve", "thirteen", "fourteen", "fifteen", "sixteen", "seventeen", "eighteen", "nineteen"];
    
        // Round to two decimal points and format as a string
        var str = parseFloat(amount).toFixed(2);
    
        // Extract the integer part and the fraction part
        var intStr = str.substring(0, str.length - 3);
        var frac = str.substring(str.length - 2);
    
        // Compute the number of three-digit groups
        var tot = "";
        var len = intStr.length;
        var grp = Math.floor(len / 3) + (len % 3 == 0 ? 0 : 1);
    
        // For each group ...
        for (var g = grp; g > 0; --g) {
            var p = len - 3 * g;
            var s = "";
    
            // Format the hundreds
            if (p >= 0 && intStr[p] != '0') {
                s += sing[parseInt(intStr[p])] + " hundred";
            }
    
            // Format values between 1 and 99
            if (p >= -1) {
                if (intStr[p + 1] < '2') {
                    if (s != "") s += " ";
                    s += sing[10 * parseInt(intStr[p + 1]) + parseInt(intStr[p + 2])];
                } else {
                    if (s != "") s += " ";
                    s += dec[parseInt(intStr[p + 1])];
                    if (intStr[p + 2] > '0') {
                        s += '-' + sing[parseInt(intStr[p + 2])];
                    }
                }
    
            // Special case if amount < 10
            } else if (intStr[p + 2] > '0') {
                if (s != "") s += " ";
                s += sing[parseInt(intStr[p + 2])];
            }
    
            // Add exponent descriptor
            if (s != "") {
                var e = exp[g - 1];
                if (e != "") {
                    s += " " + e;
                }
            }
    
            // Append to total string
            if (tot != "") tot += " ";
            tot += s;
        }
    
        // Append "dollar(s)"
        var d = parseInt(intStr);
        if (d == 1) {
            tot += " dollar";
        } else if (d > 1) {
            tot += " dollars";
        }
    
        // Append fractional part, if not zero
        if (frac != "00") {
            if (tot != "") tot += " and ";
            var c = "";
            if (frac[0] < '2') {
                c = sing[10 * parseInt(frac[0]) + parseInt(frac[1])];
            } else {
                c = dec[parseInt(frac[0])];
                if (frac[1] > '0') {
                    c += '-' + sing[parseInt(frac[1])];
                }
            }
            tot += c + (frac == "01" ? " cent" : " cents");
        }
    
        // Special case if amount == 0
        if (tot == "") tot = "zero";
    
        return tot;
    }
    </script>
    
    
    <input type="button" value="to dollars" onclick="test.rnum.value = spellOut(test.inum.value);"><br><br>
    <textarea name="rnum" cols="40" rows="5"></textarea></form></div><p>
    <form name="test"><input type="text" name="inum" value="" size="18"><br><br>
    
    
    </body>
    
    </html>
    Again PMW57
    I can't get anything back using the same code as above but with your script,

    Code:
    floatval = 1.02;
    myresult = makewords(floatval);
    document.write(myresult + '<br>');
    document.write(sprintf('The value is %0.2f<br>', floatval) + '<br>');
    This code use to return a string on the page but I can't get it to do anything any pointers would be very welcome.
    I've been wrestling with it between crimbo shopping driving me mad

    both the shopping and the code,
    Many Thanks
    Steve
    Merry Christmas to you all and you're family, and Have a good new year.

  12. #12
    SitePoint Author silver trophybronze trophy

    Join Date
    Nov 2004
    Location
    Ankh-Morpork
    Posts
    12,159
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    Try using DOM methods instead of relying on IE's bad habit of polluting the global namespace with every form element's name:
    Code:
    <input type="button" value="to dollars" onclick="document.getElementById('rnum').value = spellOut(document.getElementById('inum').value);"><br><br>
    <textarea name="rnum" id="rnum" cols="40" rows="5"></textarea></form></div><p>
    <form name="test"><input type="text" name="inum" id="inum" value="" size="18">
    Birnam wood is come to Dunsinane

  13. #13
    SitePoint Member
    Join Date
    Dec 2007
    Posts
    23
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    Me Again

    Sorry but all I keep getting is "undefined dollars and undefined cents"

    other results are :

    0 = zero, 1 = dollar (not one dollar), 2 = dollars (not two dollars)

    all other (known) numbers input just return "undefined dollars and undefined cents"
    I'm not sure if its me or the javascript code thats wrong could someone pass there expert eye over it for me,
    I've been playing with it and not getting anywhere,
    any advice much appreciated.

    many thanks

    Steve.

    Here's the Code:
    Code:
    <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
        "http://www.w3.org/TR/html4/loose.dtd">
    
    <html>
    
    <head>
      <title></title>
    </head>
    
    <body>
    
    
    <script type="text/javascript">
    
    function spellOut(amount) {
        var exp = ["", "thousand", "million", "billion", "trillion"];
        var dec = ["", "", "twenty", "thirty", "forty", "fifty", "sixty", "seventy", "eighty", "ninety"];
        var sing = ["", "one", "two", "three", "four", "five", "six", "seven", "eight", "nine", "ten",
                    "eleven", "twelve", "thirteen", "fourteen", "fifteen", "sixteen", "seventeen", "eighteen", "nineteen"];
    
        // Round to two decimal points and format as a string
        var str = parseFloat(amount).toFixed(2);
    
    
        // Extract the integer part and the fraction part
        var intStr = str.substring(0, str.length - 3);
        var frac = str.substring(str.length - 2);
    
        // Compute the number of three-digit groups
        var tot = "";
        var len = intStr.length;
        var grp = Math.floor(len / 3) + (len % 3 == 0 ? 0 : 1);
    
        // For each group ...
        for (var g = grp; g > 0; --g) {
            var p = len - 3 * g;
            var s = "";
    
            // Format the hundreds
            if (p >= 0 && intStr[p] != '0') {
                s += sing[parseInt(intStr[p])] + " hundred";
            }
    
            // Format values between 1 and 99
            if (p >= -1) {
                if (intStr[p + 1] < '2') {
                    if (s != "") s += " ";
                    s += sing[10 * parseInt(intStr[p + 1]) + parseInt(intStr[p + 2])];
                } else {
                    if (s != "") s += " ";
                    s += dec[parseInt(intStr[p + 1])];
                    if (intStr[p + 2] > '0') {
                        s += '-' + sing[parseInt(intStr[p + 2])];
                    }
                }
    
            // Special case if amount < 10
            } else if (intStr[p + 2] > '0') {
                if (s != "") s += " ";
                s += sing[parseInt(intStr[p + 2])];
            }
    
            // Add exponent descriptor
            if (s != "") {
                var e = exp[g - 1];
                if (e != "") {
                    s += " " + e;
                }
            }
    
            // Append to total string
            if (tot != "") tot += " ";
            tot += s;
        }
    
        // Append "dollar(s)"
        var d = parseInt(intStr);
        if (d == 1) {
            tot += " dollar";
        } else if (d > 1) {
            tot += " dollars";
        }
    
        // Append fractional part, if not zero
        if (frac != "00") {
            if (tot != "") tot += " and ";
            var c = "";
            if (frac[0] < '2') {
                c = sing[10 * parseInt(frac[0]) + parseInt(frac[1])];
            } else {
                c = dec[parseInt(frac[0])];
                if (frac[1] > '0') {
                    c += '-' + sing[parseInt(frac[1])];
                }
            }
            tot += c + (frac == "01" ? " cent" : " cents");
        }
    
        // Special case if amount == 0
        if (tot == "") tot = "zero";
    
        return tot;
    }
    
    
    </script>
    
    <form id="test" name="test"><input type="text" name="inum" id="inum" value="">
    
    <input type="button" value="to dollars" onclick="document.getElementById('rnum').value = spellOut(document.getElementById('inum').value);"><br><br>
    
    <textarea name="rnum" id="rnum" cols="40" rows="5"></textarea></form>
    
    
    </body>
    
    </html>

  14. #14
    Unobtrusively zen silver trophybronze trophy
    paul_wilkins's Avatar
    Join Date
    Jan 2007
    Location
    Christchurch, New Zealand
    Posts
    14,527
    Mentioned
    84 Post(s)
    Tagged
    4 Thread(s)
    It looks like it works fine in Firefox but on IE it doesn't because the script is trying to access parts of a string by using an array notation.

    The version that I transcribed from PHP to JavaScript works properly across both Firefox and IE.
    The sprintf (which required a separate library) has been eradicated from the code now, as parseFloat(numval).toFixed(2) achieves the same desired result.

    Please feel free to give use the following code instead.

    Code JavaScript:
    //*************************************************************
    // this function converts an amount into alpha words
    // and adds the words dollars and cents. Pass it a float.
    // works up to 999,999,999.99 dollars
    //*************************************************************
     
    function makewords(numval)
    {
        var moneystr = '';
        var workword;
        var workval, milval, thouval, dollarval, workstr, intstr, workint;
        // handle the millions
        milval = parseInt(numval / 1000000, 10);
        if (milval > 0)
        {
            moneystr = getwords(milval) + ' Million';
        }
     
        // handle the thousands
        workval = numval - (milval * 1000000); // get rid of millions
        thouval = parseInt(workval / 1000, 10);
        if (thouval > 0)
        {
            workword = getwords(thouval);
            if (moneystr === '')
            {
                moneystr = workword + ' Thousand';
            }
            else
            {
                moneystr += ' ' + workword + ' Thousand';
            }
        }
     
        // handle all the rest of the dollars
        workval = workval - (thouval * 1000); // get rid of thousands
        dollarval = parseInt(workval, 10);
        if (moneystr === '')
        {
            if (dollarval > 0)
            {
                moneystr = getwords(dollarval);
            }
            else
            {
                moneystr = 'Zero';
            }
        }
        else // non zero values in hundreds and up
        {
            workword = getwords(dollarval);
            moneystr += ' ' + workword;
        }
     
        // plural or singular 'dollar'
        workval = parseInt(numval, 10);
        if (workval === 1)
        {
            moneystr += ' Dollar And ';
        }
        else
        {
            moneystr += ' Dollars And ';
        }
     
        // do the pennies - use printf so that we get the
        // same rounding as printf
        workstr = parseFloat(numval).toFixed(2); // convert to a string
        intstr = workstr.substr(workstr.length - 2, 2);
        workint = parseInt(intstr, 10);
        if (workint === 0)
        {
            moneystr += 'Zero';
        }
        else
        {
            moneystr += getwords(workint);
        }
        if (workint === 1)
        {
            moneystr += ' Cent';
        }
        else
        {
            moneystr += ' Cents';
        }
     
        // done - let's get out of here!
        return moneystr;
    }
    //************************************************************
    // this function creates word phrases in the range of 1 to 999
    // pass it an integer value
    //************************************************************
    function getwords(workval)
    {
        var numwords = [
            '',
            'One',
            'Two',
            'Three',
            'Four',
            'Five',
            'Six',
            'Seven',
            'Eight',
            'Nine',
            'Ten',
            'Eleven',
            'Twelve',
            'Thirteen',
            'Fourteen',
            'Fifteen',
            'Sixteen',
            'Seventeen',
            'Eightteen',
            'Nineteen',
            'Twenty'
        ];
        numwords[30] = 'Thirty';
        numwords[40] = 'Forty';
        numwords[50] = 'Fifty';
        numwords[60] = 'Sixty';
        numwords[70] = 'Seventy';
        numwords[80] = 'Eighty';
        numwords[90] = 'Ninety';
     
        var retstr, workstr;
        var hundval, tempval, unitval;
     
        retstr = '';
        // handle the 100's
        hundval = parseInt(workval / 100, 10);
        if (hundval > 0)
        {
            retstr = numwords[hundval] + ' Hundred';
        }
     
        // handle units and teens
        workstr = '';
        var tensval = workval - (hundval * 100); // dump the 100's
        if ((tensval < 20) && (tensval > 0))// do the teens
        {
            workstr = numwords[tensval];
        }
        else // got to break out the units and tens
        {
            tempval = parseInt(tensval / 10, 10) * 10; // dump the units
            workstr = numwords[tempval]; // get the tens
            unitval = tensval - tempval; // get the unit value
            if (unitval > 0)
            {
                workstr += ' ' + numwords[unitval];
            }
        }
     
        // join all the parts together and leave
        if (workstr !== '')
        {
            if (retstr !== '')
            {
                retstr += ' ' + workstr;
            }
            else
            {
                retstr = workstr;
            }
        }
        return retstr;
    }

  15. #15
    SitePoint Author silver trophybronze trophy

    Join Date
    Nov 2004
    Location
    Ankh-Morpork
    Posts
    12,159
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    IE doesn't support JavaScript, but uses it's own, proprietary thing called JScript. As usual, it's a bad clone of something else.
    If you replace the array notation for strings with the .charAt() function, it should work:
    Code JavaScript:
    function spellOut(amount) {
        var exp = ["", "thousand", "million", "billion", "trillion"];
        var dec = ["", "", "twenty", "thirty", "forty", "fifty", "sixty", "seventy", "eighty", "ninety"];
        var sing = ["", "one", "two", "three", "four", "five", "six", "seven", "eight", "nine", "ten",
                    "eleven", "twelve", "thirteen", "fourteen", "fifteen", "sixteen", "seventeen", "eighteen", "nineteen"];
     
        // Round to two decimal points and format as a string
        var str = parseFloat(amount).toFixed(2);
     
     
        // Extract the integer part and the fraction part
        var intStr = str.substring(0, str.length - 3);
        var frac = str.substring(str.length - 2);
     
        // Compute the number of three-digit groups
        var tot = "";
        var len = intStr.length;
        var grp = Math.floor(len / 3) + (len &#37; 3 == 0 ? 0 : 1);
     
        // For each group ...
        for (var g = grp; g > 0; --g) {
            var p = len - 3 * g;
            var s = "";
     
            // Format the hundreds
            if (p >= 0 && intStr.charAt(p) != '0') {
                s += sing[parseInt(intStr.charAt(p))] + " hundred";
            }
     
            // Format values between 1 and 99
            if (p >= -1) {
                if (intStr.charAt(p + 1) < '2') {
                    if (s != "") s += " ";
                    s += sing[10 * parseInt(intStr.charAt(p + 1)) + parseInt(intStr.charAt(p + 2))];
                } else {
                    if (s != "") s += " ";
                    s += dec[parseInt(intStr.charAt(p + 1))];
                    if (intStr.charAt(p + 2) > '0') {
                        s += '-' + sing[parseInt(intStr.charAt(p + 2))];
                    }
                }
     
            // Special case if amount < 10
            } else if (intStr.charAt(p + 2) > '0') {
                if (s != "") s += " ";
                s += sing[parseInt(intStr.charAt(p + 2))];
            }
     
            // Add exponent descriptor
            if (s != "") {
                var e = exp[g - 1];
                if (e != "") {
                    s += " " + e;
                }
            }
     
            // Append to total string
            if (tot != "") tot += " ";
            tot += s;
        }
     
        // Append "dollar(s)"
        var d = parseInt(intStr);
        if (d == 1) {
            tot += " dollar";
        } else if (d > 1) {
            tot += " dollars";
        }
     
        // Append fractional part, if not zero
        if (frac != "00") {
            if (tot != "") tot += " and ";
            var c = "";
            if (frac.charAt(0) < '2') {
                c = sing[10 * parseInt(frac.charAt(0)) + parseInt(frac.charAt(1))];
            } else {
                c = dec[parseInt(frac.charAt(0))];
                if (frac.charAt(1) > '0') {
                    c += '-' + sing[parseInt(frac.charAt(1))];
                }
            }
            tot += c + (frac == "01" ? " cent" : " cents");
        }
     
        // Special case if amount == 0
        if (tot == "") tot = "zero";
     
        return tot;
    }

    I'm on Linux here, so I can't actually test in IE at the moment.
    Birnam wood is come to Dunsinane

  16. #16
    SitePoint Member
    Join Date
    Dec 2007
    Posts
    23
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    Top Christmas Present guys, Crack open a beer, you've both earned it,
    both scripts work in IE and Opera, I don't have firefox, its hard to know who is using what browser, I've had problems with IE compatibility before,
    how can one of the leading browsers avoid such basic standards,
    its about time they all got a kick up the backside and got their act together.
    I bet you have both said this a few times.

    Once again I'm indebted to you both,

    Thanks Chaps

    Steve.


    Merry Crimbo.

  17. #17
    SitePoint Author silver trophybronze trophy

    Join Date
    Nov 2004
    Location
    Ankh-Morpork
    Posts
    12,159
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    Quote Originally Posted by steve 727 View Post
    its about time they all got a kick up the backside and got their act together.
    Actually, Opera recently filed an anti-trust complaint against Microsoft with the European Commission, asking that the EC require Microsoft to be more standards compliant!
    Birnam wood is come to Dunsinane

  18. #18
    Unobtrusively zen silver trophybronze trophy
    paul_wilkins's Avatar
    Join Date
    Jan 2007
    Location
    Christchurch, New Zealand
    Posts
    14,527
    Mentioned
    84 Post(s)
    Tagged
    4 Thread(s)
    Quote Originally Posted by AutisticCuckoo View Post
    Actually, Opera recently filed an anti-trust complaint against Microsoft with the European Commission, asking that the EC require Microsoft to be more standards compliant!
    I don't think that it's about standards, rather I suspect that Opera isn't pleased that IE is so tightly integrated into the OS.

    IE8 in devlopment now already passes the Acid Test 2 with flying colours.

    Now me, I'm a firefox boy through and through, but it's good to see that Microsoft are putting the effort in. The carrot is often much more effective than the stick.

  19. #19
    SitePoint Author silver trophybronze trophy

    Join Date
    Nov 2004
    Location
    Ankh-Morpork
    Posts
    12,159
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    It's both, actually. There were two parts in that complaint. One is that IE is too tightly bound to Windows, so that you can't uninstall it. The other part was asking the EC to require Microsoft to support web standards. It's difficult for other browser vendors when they have to emulate undocumented behaviour in IE, in order to be render the millions of badly written web pages that rely on IE bugs and quirks.

    I agree that it's a good sign that an internal build of IE8 has passed the Acid2 test, though. Unfortunately it won't do any good for the millions and millions of IE6 users out there who cannot upgrade because they run Win XP or older.
    Birnam wood is come to Dunsinane

  20. #20
    SitePoint Member
    Join Date
    Dec 2007
    Posts
    23
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    Great news if it all goes to plain, but you know how long the bureaucratic way takes, we will probably all be in our boxes by then

    Do you not think there will be an upgrade for IE8, I run XP (for my sins) and upgraded from IE6 to IE7 with no problems, except for the usual slow loading bug ridden MS software, that we all have come to live with,
    why do we have to load tons of rubbish onto our hard drives that we will never use, like 30 different language etc. most folk don't even know half of whats on the computer and don't care.
    my first computer (if you can call it that) was a Vic 20 three and a half k internal memory and took years to load anything on it via cassette.
    but because memory was tight code was more slick,
    now it's just bulk junk code with most of the software, and of course machine code was use for size and speed then, I wonder how mush faster windows would run in machine code ?

  21. #21
    Unobtrusively zen silver trophybronze trophy
    paul_wilkins's Avatar
    Join Date
    Jan 2007
    Location
    Christchurch, New Zealand
    Posts
    14,527
    Mentioned
    84 Post(s)
    Tagged
    4 Thread(s)

    Machine code

    Quote Originally Posted by steve 727 View Post
    I wonder how mush faster windows would run in machine code ?
    You should have a chat with Steve Gibson then. He still writes most of his programs in machine code and it doesn't appear to have had a negative impact on things.

  22. #22
    SitePoint Author silver trophybronze trophy

    Join Date
    Nov 2004
    Location
    Ankh-Morpork
    Posts
    12,159
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    Quote Originally Posted by steve 727 View Post
    Do you not think there will be an upgrade for IE8
    Last I heard, IE8 would only be available for Vista.
    Birnam wood is come to Dunsinane

  23. #23
    SitePoint Member
    Join Date
    Dec 2007
    Posts
    23
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    Hi Chaps

    No IE8 upgrade
    I hope I ain't pestering you too much honest this is the last question about the javascript, its a bit hard to explain,

    with in the script I have to have exceptions, as I will convert this script to French German & Spanish, and with these there are complications,

    Example's:

    twenty one (uk) einundzwanzig (1 and 20) (D) vingt et une (20 and 1) (fr)

    Some languages say 21, some 20&1, others 1&20,

    to keep it simple confused: ) each language will have its own script.

    I've tried adding IF statements but not getting anywhere I've managed to

    reverse twenty one, to einundzwanzig (1&20) with little trouble, but with the French the 20&1 thing is only for 21, 31, 41, 51, 61,
    then 71 is 60+11 (soixante onze) so you can see my need for exceptions

    can it be something like:

    if = 71 then 'soixante onze' ( but in real javascript)

    I would need this for all 1000's, 100's, and the fractions (cents)

    I hope this is clear if not let me know.

  24. #24
    SitePoint Enthusiast
    Join Date
    Dec 2007
    Posts
    66
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    Did you try out my example at all? It would not be too difficult to extend it to support multiple languages, but obviously you'd need to have a really good understanding of the rules for each language. Here's my original example, modified slightly to show how you could support multiple languages:

    Code:
    <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN"
     "http://www.w3.org/TR/html4/strict.dtd">
    <html>
    <head>
      <meta http-equiv="Content-Type" content="text/html; charset:utf-8">
      <title></title>
      <script type="text/javascript" src="http://yui.yahooapis.com/2.3.1/build/yahoo-dom-event/yahoo-dom-event.js"></script>
    </head>
    <body>
    <div id="container">
    
    <script type="text/javascript">
    var MoneyConverter = function() {
        var num = [" zero", " one", " two", " three", " four", " five", " six", " seven", " eight", " nine"];
        var teens = [" ten", " eleven", " twelve", " thirteen", " fourteen", " fifteen", " sixteen", " seventeen", " eighteen", " nineteen"];
        var tennums = [" twenty", " thirty", " forty", " fifty", " sixty", " seventy", " eighty", " ninety"];
        var frtwenties = ["];
        return {
            /**
             * Convert a decimal value to textual dollar and cents
             * @param {Float} amt The decimal value
             * @param {String} lan The language to return it in
             * @return The textual dollar and cents value
             */
            toTextDollars : function(amt, lan) {
                if (amt > 999999999.99 || amt < 0) {
                    return "invalid amount";
                }
                var decimal = amt - Math.floor(amt);
                switch (lan) {
                    case 'fr':
                        return this.toTextualValue(amt, lan) + (amt == 1? " franc " : " francs ") + this.decimalTextualValue(decimal, lan);
                        break;
                    case 'en':
                    default:
                        return this.toTextualValue(amt, lan) + (amt == 1? " dollar " : " dollars ") + this.decimalTextualValue(decimal, lan);
                        break;
                }
                
            }, 
            toTextualValue : function(amt, lan) {
                switch (lan) {
                    case 'fr':
                        // TODO: figure rules for showing french numbers
                        return parseInt(amt);
                        break;
                    case 'en':
                    default:
                        if (amt == 0) {
                            return "zero";
                        }            
                
                        var result = "";
                        var millions = Math.floor(amt / 1000000);
                        var m = millions * 1000000;
                        var thousands = Math.floor((amt - m) / 1000);
                        var th = thousands * 1000;
                        var hundreds = Math.floor((amt - (m + th)) / 100);
                        var h = hundreds * 100;
                        var tens = Math.floor((amt - (m + th + h)) / 10);
                        var t = tens * 10;
                        var ones = Math.floor((amt - (m + th + h + t)));
                
                        if (millions >= 1) {
                            result += this.toTextualValue(millions) + " million";
                        }
                        if (thousands >= 1) {
                            result += this.toTextualValue(thousands) + " thousand";
                        }
                        if (hundreds >= 1) {
                            result += this.toTextualValue(hundreds) + " hundred";
                        }
                        if (tens > 0) {
                            if (tens == 1) {
                                result += teens[ones];
                            }
                            else {
                                result += tennums[tens - 2];
                            } 
                        }
                        if (ones > 0 && tens != 1) {
                            result += num[ones];
                        }
                         
                        return result;
                        break;
                }
            },
            decimalTextualValue : function(d, lan) { // 1 - 99
                switch (lan) {
                    case 'fr':
                        // TODO: figure rules for showing french numbers
                        return d;
                        break;
                    case 'en':
                    default:
                        var dint = d * 100;
                        if (dint > 0) {
                            return " and " + this.toTextualValue(dint) + " cents";
                        }
                        else {
                            return "";
                        }
                        break;
                }
            }
        };
    }();
    
    alert(MoneyConverter.toTextDollars(125222121.4, "fr"));
    </script>
    
    
    </div>
    </body>
    </html>

  25. #25
    SitePoint Enthusiast
    Join Date
    Dec 2007
    Posts
    66
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    I didn't finish that example before posting it, and there is an error in it. Delete this line:

    var frtwenties = ["];

    I was going to show the 21 example for french, but ran out of time.


Bookmarks

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •