gpt4 book ai didi

string - 数字到字符串 - 如何将 150 变成 "One Hundred and Fifty"

转载 作者:塔克拉玛干 更新时间:2023-11-03 02:49:53 24 4
gpt4 key购买 nike

只是想知道是否有任何库可以轻松地将数字转换为 javascript、jquery、php、python 等中的字符串表示...

例如:我需要将 1,210 变成“一千二百一十”。

这个程序有名字吗?

最佳答案

Javascript 解决方案。支持从负无穷大到无穷大的所有整数:

var GetWord;
(function(){
GetWord = function (number) {//number must be an integer
return (function f(number){
var output = [];
var is_negative = number < 0;
number = Math.abs(number);

var chunks = [];
for (var x = count_names.length - 1, limit = 0; x >= limit; --x) {
var chunk = Math.floor(number / counts[x]);
if (chunk !== 0) {
output.push(GetWord(chunk) + " " + count_names[x]);
}
chunks[x] = chunk;
number -= chunk * counts[x];
}
if (number !== 0) {
if (number <= 19) {
output.push(number_names[number]);
} else {
var tens = Math.floor(number / 10);
number -= tens * 10;
if (number === 0) {
output.push(number_names2[tens - 2]);
} else {
output.push(number_names2[tens - 2] + " " + GetWord(number));
}
}
}
if (output.length > 2) {
for (var x = 0, limit = output.length - 1; x < limit; ++x) {
output[x] += ","
}
}
if (output.length > 1) {
var ubound = output.length - 1;
output[output.length] = output[ubound];
output[ubound] = "and";
}
if (is_negative) {
output.splice(0, 0, "negative");
}
return output;
})(number).join(" ");
};
var number_names = ["zero", "one", "two", "three", "four", "five", "six", "seven", "eight", "nine", "ten", "eleven", "twelve", "thirteen", "fourteen", "fifteen", "sixteen", "seventeen", "eighteen", "nineteen"];
var number_names2 = ["twenty", "thirty", "forty", "fifty", "sixty", "seventy", "eighty", "ninety", "hundred"]
var count_names = ["hundred", "thousand", "million", "billion", "trillion", "quadrillion", "quintillion", "sextillion", "septillion", "octillion", "nonillion", "decillion", "undecillion", "duodecillion", "tredecillion", "quattuordecillion", "quindecillion", "sexdecillion", "septendecillion", "octodecillion", "novemdecillion", "vigintillion"];
var counts = [100];
for (var x = counts.length, limit = count_names.length; x < limit; ++x) {
counts.push(Math.pow(1000, x));
}
})();

用法:

GetWord(1210); 给出一千、二百和十

GetWord(2147483647); 给出二十亿、一亿四千七百万、四十八万三千、六百四十七

GetWord(-123876124); 给出负一亿二千三百万、八十七万六千、一百二十四

如果您需要它们上限,只需将这些数组模板更改为“上限”形式即可。

关于string - 数字到字符串 - 如何将 150 变成 "One Hundred and Fifty",我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6625605/

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