gpt4 book ai didi

angularjs - 将数字转换为单词的 Angular 指令/服务(Angularjs 中需要)?

转载 作者:行者123 更新时间:2023-12-02 23:17:09 25 4
gpt4 key购买 nike

我想将数字转换为单词。就像 234 换成单词就是 234。同样,1000 将是 1000。同样,100 表示一百。

AngularJS 中是否有任何库可以实现此目的?如果那么我们将如何编写 angularjs 指令/服务以便我们可以再次使用它..

最佳答案

创建单词过滤器。

enter image description here

我从这篇博文中得到了“toWords”算法: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>

关于angularjs - 将数字转换为单词的 Angular 指令/服务(Angularjs 中需要)?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34649013/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com