2016-01-07 74 views
5

我想將數字轉換爲單詞。 234中的字將是234。同樣的1000將會是一千。同樣,100意味着一百。Angular指令/服務將數字轉換爲單詞(需要Angularjs)?

在angularjs中有沒有這樣的庫。如果那麼我們將如何寫在angularjs指令/服務,以便我們可以再次使用它。

+3

http://stackoverflow.com/questions/14766951/convert-digits- into-words-with-javascript – lee

回答

16

創建一個單詞過濾器。

enter image description here

我從這篇博客的 「毛詩補傳」 算法: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

爲什麼要做'window.toWords = toWords;'而不是僅僅包含函數'toWords()'和過濾器中的變量? – Justin

+0

感謝您的資源,非常有幫助 –

+0

是否有可能與angular2? – NunnaS