Angular directive/service to convert number into words (need in Angularjs)?

前端 未结 2 1441
臣服心动
臣服心动 2020-12-18 04:48

I want to convert number into words. Like 234 in word would be 2 hundred thirty-four. Similarly 1000 will be one thousand. Similarly 100 means one hundred.

Is ther

相关标签:
2条回答
  • 2020-12-18 04:55

    I have done this for Angular 8. It also works for float/double numbers.

    0 讨论(0)
  • 2020-12-18 05:00

    Create a words filter.

    I got the "toWords" algorithm from this blog post: http://ravindersinghdang.blogspot.com/2013/04/convert-numbers-into-words-using.html

    var app = angular.module('app',[]);
    
    app.filter('words', function() {
      function isInteger(x) {
            return x % 1 === 0;
        }
    
      
      return function(value) {
        if (value && isInteger(value))
          return  toWords(value);
        
        return value;
      };
    
    });
    
    
    var th = ['','thousand','million', 'billion','trillion'];
    var dg = ['zero','one','two','three','four', 'five','six','seven','eight','nine']; 
    var tn = ['ten','eleven','twelve','thirteen', 'fourteen','fifteen','sixteen', 'seventeen','eighteen','nineteen'];
    var tw = ['twenty','thirty','forty','fifty', 'sixty','seventy','eighty','ninety']; 
    
    
    function toWords(s)
    {  
        s = s.toString(); 
        s = s.replace(/[\, ]/g,''); 
        if (s != parseFloat(s)) return 'not a number'; 
        var x = s.indexOf('.'); 
        if (x == -1) x = s.length; 
        if (x > 15) return 'too big'; 
        var n = s.split(''); 
        var str = ''; 
        var sk = 0; 
        for (var i=0; i < x; i++) 
        {
            if ((x-i)%3==2) 
            {
                if (n[i] == '1') 
                {
                    str += tn[Number(n[i+1])] + ' '; 
                    i++; 
                    sk=1;
                }
                else if (n[i]!=0) 
                {
                    str += tw[n[i]-2] + ' ';
                    sk=1;
                }
            }
            else if (n[i]!=0) 
            {
                str += dg[n[i]] +' '; 
                if ((x-i)%3==0) str += 'hundred ';
                sk=1;
            }
    
    
            if ((x-i)%3==1)
            {
                if (sk) str += th[(x-i-1)/3] + ' ';
                sk=0;
            }
        }
        if (x != s.length)
        {
            var y = s.length; 
            str += 'point '; 
            for (var i=x+1; i<y; i++) str += dg[n[i]] +' ';
        }
        return str.replace(/\s+/g,' ');
    }
    
    window.toWords = toWords;
    <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.js"></script>
    
    <div ng-app="app">
      
      <input type="text" ng-model="name" /> {{name | words}}
    </div>

    0 讨论(0)
提交回复
热议问题