www.webdeveloper.com
Results 1 to 14 of 14

Thread: Converting numbers to words in document.write

  1. #1
    Join Date
    Jul 2012
    Posts
    7

    Question Converting numbers to words in document.write

    Hi all,

    I've been playing about with a story generator using javascript and need to convert some numbers into words and perform some basic operations like multiplication and division within the document.write. The conversion to words is what has been giving me major problems.

    I found this code for converting numbers to words but am at a complete loss as to how to implement it within document write...
    http://javascript.about.com/library/bltoword.htm

    a small example of how it's being used:
    Code:
    <script>
    
    
    address1=prompt("House number (numeric)","");
    
    document.write(" <a>"+name+"</a> didn't answer, not recognising the voice outside and silently waited. After <a>"+address1+"</a> minutes footsteps dragged themselves away from the door and the steady roar of a car on it's last legs could be heard starting up and slowly fading into the distance. ");
    </script>
    where address1 is the number and i need to be able to both turn into words and perform basic operations on it. Clearly I'm not the most advanced in javascript.

    Completely stuck! So any help would be amazing!
    THANK YOU

  2. #2
    Join Date
    Jun 2008
    Posts
    106
    You shouldn't use document.write(). It reflows the page and it's very slow. Try using
    Code:
    document.body.appendChild( document.createTextNode( 'hello world') );

    Back to your question... basically, you use a few arrays, a multi-dimensional array, or an object to figure out the word for a number.

    Here's an example for numbers 0-9:
    Code:
    var words = [
        'zero', 'one', 'two', 'three', 'four', 'five', 'six', 'seven', 'eight', 'nine'
    ];
    
    var number = 5;
    
    alert( words[number] );
    It works because each index's value contains the indexes word (e.g., words[2] is 'two').
    That's the basic idea. It gets a little complicated for numbers 10-19, but then it's easy for numbers 20 and up because you just find the prefix and then add the value.

    If you tell me the max house number a user can enter, I'll write up a little example for you.

  3. #3
    Join Date
    Dec 2005
    Location
    FL
    Posts
    7,262

    Wink

    Modifying 'tenfold's example, here is a script for the numbers from 0-99.
    Probably could be compressed a bit more, but it will at least give you an idea of the concept.

    Code:
    <!DOCTYPE html>
    <html lang="en">
    <head>
    <meta charset="UTF-8" />
    
    <title> Untitled </title>
    
    </head>
    <body>
    <div id="test"></div>
    
    <script type="text/javascript">
    var words = [
        'zero', 'one', 'two', 'three', 'four', 'five', 'six', 'seven', 'eight', 'nine',
        'ten', 'eleven', 'twelve', 'thirthteen', 'fourteen', 'fifteen'
    ];
    
    function Num2Word(N) {
      var str = '';
      if (N >= words.length) {
        if ((N > 15) && (N < 20)) { str = words[N-10]+'teen'; }
        if ((N > 19) && (N < 30)) { str = 'twenty';  if (N > 20) { str += '-'+words[N-20]; } }
        if ((N > 29) && (N < 40)) { str = 'thirty';  if (N > 30) { str += '-'+words[N-30]; } }
        if ((N > 39) && (N < 50)) { str = 'fourty';  if (N > 40) { str += '-'+words[N-40]; } }
        if ((N > 49) && (N < 60)) { str = 'fifty';   if (N > 50) { str += '-'+words[N-50]; } }
        if ((N > 59) && (N < 70)) { str = 'sixty';   if (N > 60) { str += '-'+words[N-60]; } }
        if ((N > 69) && (N < 80)) { str = 'seventy'; if (N > 70) { str += '-'+words[N-70]; } }
        if ((N > 79) && (N < 90)) { str = 'eighty';  if (N > 80) { str += '-'+words[N-80]; } }
        if ((N > 89) && (N < 100)) { str = 'ninety'; if (N > 90) { str += '-'+words[N-90]; } }
      } else { str = words[N]; }
      return str;
    };
    
    var numbers = [ ];  for (var i=0; i<100; i++) { numbers.push(i); }
    
    var str = '';
    for (var i=0; i<numbers.length; i++) { str += numbers[i] + ' = ' + Num2Word(numbers[i]) + '<br>'; }
    document.getElementById('test').innerHTML = str;
    </script>
    
    </body>
    </html>
    Last edited by JMRKER; 07-30-2013 at 11:00 PM.

  4. #4
    Join Date
    Dec 2005
    Location
    FL
    Posts
    7,262

    Wink

    Another version to display 0 to 9999.

    Code:
    <!DOCTYPE html>
    <html lang="en">
    <head>
    <meta charset="UTF-8" />
    
    <title> Untitled </title>
    
    </head>
    <body>
    <div id="test"></div>
    
    <script type="text/javascript">
    var words = [
        'zero', 'one', 'two', 'three', 'four', 'five', 'six', 'seven', 'eight', 'nine',
        'ten', 'eleven', 'twelve', 'thirteen', 'fourteen', 'fifteen', 'sixteen', 'seventeen', 'eighteen', 'nineteen'
    ];
    
    function Num2Word(N) {
      var str = '';
      if (N >= words.length) {
        if ((N >= 1000) && (N < 10000)) { n = parseInt(N/1000); str += words[n]+'-thousand '; N -= n * 1000; }
        if ((N >= 100)  && (N < 1000) ) { n = parseInt(N/100); str += words[n]+'-hundred '; N -= n * 100; }
        if ((N > 0)  && (N < 20)) { str += words[N]; }
        if ((N > 19) && (N < 30)) { str += 'twenty';  if (N > 20) { str += '-'+words[N-20]; } }
        if ((N > 29) && (N < 40)) { str += 'thirty';  if (N > 30) { str += '-'+words[N-30]; } }
        if ((N > 39) && (N < 50)) { str += 'fourty';  if (N > 40) { str += '-'+words[N-40]; } }
        if ((N > 49) && (N < 60)) { str += 'fifty';   if (N > 50) { str += '-'+words[N-50]; } }
        if ((N > 59) && (N < 70)) { str += 'sixty';   if (N > 60) { str += '-'+words[N-60]; } }
        if ((N > 69) && (N < 80)) { str += 'seventy'; if (N > 70) { str += '-'+words[N-70]; } }
        if ((N > 79) && (N < 90)) { str += 'eighty';  if (N > 80) { str += '-'+words[N-80]; } }
        if ((N > 89) && (N < 100)) { str += 'ninety'; if (N > 90) { str += '-'+words[N-90]; } }
      } else { str = words[N]; }
      return str;
    };
    
    var s=0;     var e=100;
    // var s=100;   var e=200;    // other test values
    // var s=9000;  var e=10000;  // more test values 
    var numbers = [ ];  for (var i=s; i<e; i++) { numbers.push(i); }
    
    var str = '';
    for (var i=0; i<numbers.length; i++) { str += numbers[i] + ' = ' + Num2Word(numbers[i]) + '<br>'; }
    document.getElementById('test').innerHTML = str;
    </script>
    
    </body>
    </html>
    Last edited by JMRKER; 08-01-2013 at 01:27 PM. Reason: Lightning Fast Fingers Failed Me

  5. #5
    Join Date
    Jun 2008
    Posts
    106
    @JMRKER: You have a spelling error in your code (thirthteen).



    @MaxRyan: I made a little code for you. It only handles numbers up to one million, but that should be fine for house numbers, lol.
    http://pastebin.com/hhA9r0MZ

    You can test it like this:
    Code:
    alert( num2word( prompt('Enter a number below one million.', '') ) );
    It can take a number or a string as an argument, so prompt() will work fine with it.
    It converts all strings/numbers to base10 numbers, so sending it '0100' or '100x' should be fine, too.

    Also, it's surprisingly easy to raise the max number it can take.

  6. #6
    Join Date
    Oct 2010
    Location
    Versailles, France
    Posts
    1,252
    It's not a problem to convert numbers to string or to count with European numbers

  7. #7
    Join Date
    Nov 2002
    Location
    Flint, Michigan, USA
    Posts
    587
    http://spruce.flint.umich.edu/~jalar....htm#a:NumWord

    The above link can convert numbers to and from words as large as nine hundred duotrigintillion and as small as hundred quadrillionths. That should keep you out of mischief for a minute or two.

  8. #8
    Join Date
    Jun 2008
    Posts
    106
    @jalarie: He wants to do it in his script automatically, not manually.

  9. #9
    Join Date
    Nov 2002
    Location
    Flint, Michigan, USA
    Posts
    587
    Quote Originally Posted by tenfold View Post
    @jalarie: He wants to do it in his script automatically, not manually.
    I understand that. The quoted URL is to a page that uses a pair of JavaScript functions to do exactly that. If he's interested, I'll arrange a copy of those functions to him. He could then place function calls in his page to do what he wants.

  10. #10
    Join Date
    Jun 2008
    Posts
    106
    I thought you would say that. It makes sense, but aren't those functions pretty big? This guy only needs to go up to like 1,000; maybe 10,000 but I doubt it.

  11. #11
    Join Date
    Oct 2010
    Location
    Versailles, France
    Posts
    1,252
    Here is an excerpt of my script for Great Britain. Its cut the number in triplets and use the replace method with function not to replace but to define the word string... Its give a short but compact script.

    Code:
    function triplets(n){var c='',m=0;
        if (100<=n) {m=Math.floor(n/100);c+=triplets(m)+' hundred';n-=m*100}
        n.toString().replace(/^[2-9](?=\d)/,function(a){
            c+=(m?'  and ':' ')+('twenty,thirty,forty,fifty,sixty,seventy,eighty,ninety'.split(',')[a-2]);n-=(+a)*10});
        if (n==0) return c;else if (c && n<10) c+='-';
        return c+' '+'one,two,three,four,five,six,seven,eight,nine,ten,eleven,twelve,thirteen,fourteen,fifteen,sixteen,seventeen,eighteen,nineteen'.split(',')[n-1];
    }
    function anyNumber(n){var lng,isS,chn='';
        wds=',thousand,million,thousand million'.split(',');
        n.toString().replace(/(\d{1,3})(?=((\d\d\d)*)$)/g,function(a,b,c){ 
           lng=c.toString().length/3;
           isS=triplets(m=a.replace(/^0+/,''));
           if (isS) chn+=((!lng) && m<100 && /thousand$/.test(chn)?' and ':' ')+isS.replace(/- /g,'-')+' '+wds[lng];
        });
        return chn.replace(/\s+/g,' ');
    }
    // Use 
    alert(anyNumber(897563))
    The script is made for positive numbers (0 give an empty string) less than 1,000,000,000,000 which should be enough by choosing well units...
    For USA replace the thousand million by billion and remove the word and.
    Unless I'm mistaken ?
    Last edited by 007Julien; 08-10-2013 at 06:17 AM.

  12. #12
    Join Date
    Nov 2002
    Location
    Flint, Michigan, USA
    Posts
    587
    Quote Originally Posted by tenfold View Post
    I thought you would say that. It makes sense, but aren't those functions pretty big? This guy only needs to go up to like 1,000; maybe 10,000 but I doubt it.
    The base code is what it is. To get the larger numbers, I just had to add to the end of:
    Code:
        NW_Names=new Array('','Thousand','Million','Billion',
          'Trillion','Quadrillion','Quintillion','Sextillion',
          'Septillion','Octillion','Nonillion','Decillion',
          'Undecillion','Duodecillion','Tredecillion',
          'Quattuordecillion','Quindecillion','Sexdecillion',
          'Septendecillion','Octodecillion','Novemdecillion',
          'Vigintillion','unvigintillion','duovigintillion',
          'trevigintillion','quattuorvigintillion','quinvigintillion',
          'sexvigintillion','septenvigintillion','octovigintillion',
          'novemvigintillion','trigintillion','untrigintillion',
          'duotrigintillion'
        );

  13. #13
    Join Date
    Oct 2010
    Location
    Versailles, France
    Posts
    1,252
    Congratulations. Its a very good linguistic work...
    And it is even more beautiful than it is, as the Eiffel tower, totally useless !

  14. #14
    Join Date
    Nov 2002
    Location
    Flint, Michigan, USA
    Posts
    587
    Quote Originally Posted by 007Julien View Post
    Congratulations. Its a very good linguistic work...
    And it is even more beautiful than it is, as the Eiffel tower, totally useless !
    It's not TOTALLY useless; it has two interesting facets:

    1. It demonstrates easy expandability. The routine is written in such a way that the base code does not need to be changed to add functionality. I agree that having that many digits is probably not needed, but the lesson is there none the less.

    2. It provoked a response from you. Good to hear from you!
    Last edited by jalarie; 08-11-2013 at 09:08 PM. Reason: spelling error

Thread Information

Users Browsing this Thread

There are currently 1 users browsing this thread. (0 members and 1 guests)

Tags for this Thread

Posting Permissions

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



Recent Articles