Convert values to English in the form
This case is from Jing, a three-party developer 」
1. Usage scenarios
If the built application involves some external orders, the value must be expressed in English. You can refer to this document to convert the value to English.
This exampleYou can convert up to 12 pure digits and 2 decimal places. For example:999999999999.99.
2. Implement functions
2.1 Configuration page
(1) configuration page
(2) configuration function
Value to Chinese function:
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. Achieve results
4. Try it online
This doc is generated using machine translation. Any discrepancies or differences created in the translation are not binding and have no legal effect for compliance or enforcement purposes.
本文档对您是否有帮助?