Javascript numbers to words - vigesimal

。_饼干妹妹 提交于 2019-12-06 02:05:35

The following function should give you an idea how to approach this:

function getnum(s){
    var n = parseInt(s);

    if( 1 <= n && n <= 20 ){ alert(units[n]); }

    if( (40 <= n && n <= 99) || (120 <= n && n <= 199) ){
      var q = Math.floor(n / 20);
      var r = n % 20;

      !r && (alert (units[q] + ' ' + units[20]));

      r && (alert (units[r] + ' and ' + units[q] + ' ' + units[20]));    
    }    
}

Now you should be able to figure out the conversion for 100 <= number <= 119. Also similar for 21 <= number <= 39.

Let's work through an example: Consider the number x.

First figure out how many 100's are in the number. We do that like this: x/100 since integer division truncates off any remainder. So that's our first segment: units[x/100] + " hundred"

Now let's do the remainder, given by y=x%100. There are y/20 twenties. And y%20 remaining. So the rest of the string is units[y%20] + " and " + units[y/20] + " " units[20].

This isn't 100% perfect just yet since it doesn't correctly handle numbers with no remainders like 640. But those are just a few special casees which I'm sure you can figure out without any trouble.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!