跳到主要内容

表单中将数值转成英文

本案例来自三方开发者「Jing」

1. 使用场景

搭建的应用如果会涉及到一些对外订单,需要使用英文表示数值,可以参考本文档实现数值转英文。

本例最高支持12位纯数字和2位小数的数值转化,例:999999999999.99

2. 实现功能

2.1 配置页面

(1)配置页面

(2)配置功能

数值转中文函数:

export function numberToWords(num) {
// 1到19
const unitObj = {
1: " One",
2: " Two",
3: " Three",
4: " Four",
5: " Five",
6: " Six",
7: " Seven",
8: " Eight",
9: " Nine",
10: " Ten",
11: " Eleven",
12: " Twelve",
13: " Thirteen",
14: " Fourteen",
15: " Fifteen",
16: " Sixteen",
17: " Seventeen",
18: " Eighteen",
19: " Nineteen"
}
// 20, 30 ~ 90
const tenObj = {
2: " Twenty",
3: " Thirty",
4: " Forty",
5: " Fifty",
6: " Sixty",
7: " Seventy",
8: " Eighty",
9: " Ninety"
}
// 数字大小限制为Billion级别,所以只需要以下几个就行了
const unitAry = ["", " Thousand", " Million", " Billion"];

if ((String(num).indexOf('.')) != -1) {
// 含小数
// 截取小数部分字符串
const numArray = String(num).split('.');
return numberToWordsFc(numArray[0]) + " Point " + numberToWordsFc(numArray[1]);
} else {
// 不含小数
return numberToWordsFc(num);
};

function numberToWordsFc(num) {
// 这个数决定选取当前的数字块后面加的单位
let count = 0;
let str = "";
if (num === 0) return "Zero";
if (num < 0) {
num = Math.abs(num);
// 将数字按照3位分割 分割后的数字 除了后面附带的单位不一样,其他的都相同处理方法
console.log(111);
while (num > 0) {
const newNum = num % 1000;
const newNumStr = convertNumToStr(newNum);
str = (newNumStr === "" ? "" : (newNumStr + unitAry[count])) + (str === "" ? "" : (" " + str));
num = parseInt(num / 1000);
count++;
};
return "Minus " + str.replace(/s{2,}/g, " ");
} else {
// 将数字按照3位分割 分割后的数字 除了后面附带的单位不一样,其他的都相同处理方法
while (num > 0) {
const newNum = num % 1000;
const newNumStr = convertNumToStr(newNum);
str = (newNumStr === "" ? "" : (newNumStr + unitAry[count])) + (str === "" ? "" : (" " + str));
num = parseInt(num / 1000);
count++;
};
return str.replace(/s{2,}/g, " ");
}
}

function convertNumToStr(num) {
let str = "";
const n1 = parseInt(num / 100);
if (n1 > 0) {
str += unitObj[n1] + " Hundred";
}
let n2 = num % 100;
if (n2 > 19) {
const tenCount = parseInt(n2 / 10);
const geCount = n2 % 10;
str += tenObj[tenCount];
if (geCount > 0) {
str += unitObj[geCount];
}
} else if (n2 > 0) {
str += unitObj[n2];
}
return str.trim();
}
}

3. 实现效果

4. 在线试玩

Copyright © 2024钉钉(中国)信息技术有限公司和/或其关联公司浙ICP备18037475号-4