我正在尝试将数字(1,2,3 ...)转换为中文字符(一,二/两,三......)。在中文中,数字是[数百] [100] [数十] [10] [1]。例如,243将被写为2 [100] 4 [10] 3或三百四十三。有没有办法有效地做到这一点,或者我是否必须创建一个遍历每个数字并通过数组进行翻译的函数?
谢谢!
答案 0 :(得分:2)
您可以查看Number.prototype.toLocaleString Using locales
console.log(123456.789.toLocaleString('zh-u-nu-hanidec' )) // "一二三,四五六.七八九"
console.log(123456.789.toLocaleString('zh-u-nu-FullWide')) // "123,456.789"
答案 1 :(得分:1)
您只需要两个数组,一个用于每个数字的名称,另一个用于数字中数字位置的名称。像
这样的东西var digits = [ 'zero', 'one', 'two', 'three', 'four', 'five', 'six', 'seven', 'eight', 'nine' ]
var positions = [ 'ones', 'tens', 'hundreds' ];
toWords = num => String(243).split('').reduce((acc, curr, index) => {
console.log(parseInt(curr))
acc += digits[parseInt(curr)] + positions.reverse()[index]
return acc
}, "")
console.log(toWords(243))
如果您将英文单词作为中文字符,您将获得所需的结果
答案 2 :(得分:1)
我测试所有答案。我发现没有人是对的。所以我自己写一个函数。这是我的代码。
function toChineseNumber(n) {
if (!Number.isInteger(n) && n < 0) {
throw Error('请输入自然数');
}
const digits = ['零', '一', '二', '三', '四', '五', '六', '七', '八', '九'];
const positions = ['', '十', '百', '千', '万', '十万', '百万', '千万', '亿', '十亿', '百亿', '千亿'];
const charArray = String(n).split('');
let result = '';
let prevIsZero = false;
//处理0 deal zero
for (let i = 0; i < charArray.length; i++) {
const ch = charArray[i];
if (ch !== '0' && !prevIsZero) {
result += digits[parseInt(ch)] + positions[charArray.length - i - 1];
} else if (ch === '0') {
prevIsZero = true;
} else if (ch !== '0' && prevIsZero) {
result += '零' + digits[parseInt(ch)] + positions[charArray.length - i - 1];
}
}
//处理十 deal ten
if (n < 100) {
result = result.replace('一十', '十');
}
return result;
}
console.log(toChineseNumber(123));
答案 3 :(得分:0)
您可以尝试使用此软件包:chinese-numbering
the expected output should look like this:
address-family ipv4 vrf vrf2
neighbor 10.244.120.202 route-map LOCAL_PREF in
address-family ipv4 vrf vrf3
neighbor 10.249.34.129 route-map LOCAL_PREF in
address-family ipv4 vrf vrf6
neighbor 10.242.120.202 route-map LOCAL_PREF in
address-family ipv4 vrf vrf9
neighbor 10.246.88.2 route-map LOCAL_PREF in
>>>> text File <<<<
address-family ipv4 vrf vrf1
address-family ipv4 vrf vrf2
neighbor 10.244.120.202 route-map LOCAL_PREF in
address-family ipv4 vrf vrf3
neighbor 10.249.34.129 route-map LOCAL_PREF in
address-family ipv4 vrf vrf5
address-family ipv4 vrf vrf6
neighbor 10.242.120.202 route-map LOCAL_PREF in
address-family ipv4 vrf vrf7
address-family ipv4 vrf vrf8
address-family ipv4 vrf vrf9
neighbor 10.246.88.2 route-map LOCAL_PREF in
>>> code <<<<
with open('out_put.txt', 'r') as f:
for line in f.readlines():
if line.startswith('address-family'):
first_line = line.strip() # strip() removes whitespace surrounding the line
print(first_line)
second_line = next(f).strip()
print(second_line)
const cn = window.ChineseNumbering;
console.log("11 => " + cn.numberToChinese(11));
console.log("11.5 => " + cn.numberToChinese(11.5));
console.log("-3.1415 => " + cn.numberToChinese(-3.1415));
console.log("繁体: 10000 => " + cn.numberToChinese(10000, 't'));