メインコンテンツまでスキップ

フォームで数値を英語に変換します

このケースは三者開発者「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 © 2025钉钉(中国)信息技术有限公司和/或其关联公司浙ICP备18037475号-4