Commit ef62254f authored by niuyutian's avatar niuyutian

代码提交

parent c75644ed
Pipeline #311 canceled with stages
......@@ -8,6 +8,54 @@ const units2 = [
'角', '分', '厘', '毫', '丝'
];
export default function numberToWords(num: number): string {
return 'one';
export default function numberToWords(input: string|number): string {
input=String(input)
let newInput
if (input === undefined || input === null || input === '' || !/^[\-]?\d{0,21}(\.\d{0,3})?$/.test(input)) {
return input;
}
if(/[\-]\d{0,21}(\.\d{0,3})?$/.test(input)){
newInput = input.replace(/-/,"");
}else{
newInput = input;
}
newInput = newInput.replace(/^0+$/, "0").replace(/^0+([1-9].*)/, "$1");
const CN1 = ['零', '壹', '贰', '叁', '肆', '伍', '陆', '柒', '捌', '玖'];
const CN2 = ['元', '万', '亿','兆','京','垓'];
const CN3 = ['', '拾', '佰', '仟'];
const CN4 = ['角', '分', '厘'];
newInput = newInput + "";
const arr = newInput.split(".");
let int = arr[0], dot = arr[1];//分成整数和小数两个部分
let intArr = int.split("");
let counter = 0;
for (let i = intArr.length - 1; i >= 0; i--) {
intArr[i] = CN1[intArr[i]] + CN3[counter % 4];
if (counter % 4 == 0) {
intArr[i] += CN2[counter / 4];
}
counter++;
}
int = intArr.join("").replace(/(零仟|零佰|零拾)/g, "零").replace(/零+/g, "零").replace(/零(元|万|亿|兆|京|垓)/g, "$1").replace(/亿万/, "亿").replace(/兆亿/,"兆").replace(/京兆/,"京").replace(/垓京/,"垓");
if (int === '元') {
int = '零元';
}
if (!dot || /^0+$/.test(dot)) {
if(/^[\-]\d{0,21}(\.\d{0,3})?$/.test(input)){
let value = input.length==1?"负":"负"+int+"整"
return value;
}else{
return int + "整";
}
} else {
dot = dot.split("").map(function (item, index) {
return CN1[item] + CN4[index];
}).join("");
dot = dot.replace(/(零角|零分|零厘)/g, "零").replace(/零+/g, "零").replace(/零$/, "");
if(/^[\-]\d{0,21}(\.\d{0,3})?$/.test(input)){
return "负" + int + dot;
}else{
return int + dot;
}
}
}
\ No newline at end of file
......@@ -2,8 +2,20 @@ import { describe, it, expect } from 'vitest'
import numberToWords from '../../src/money/numberToWords'
describe('numberToWords', () => {
it('1 return 壹元', () => {
expect(numberToWords(1)).toBe('壹元')
it('1 toBe 壹元整', () => {
expect(numberToWords(1)).toBe('壹元整')
})
it('1.01 toBe 壹元零壹分', () => {
expect(numberToWords(1.01)).toBe('壹元零壹分')
})
it('17916.67 toBe 壹万柒仟玖佰壹拾陆元陆角柒分', () => {
expect(numberToWords(17916.67)).toBe('壹万柒仟玖佰壹拾陆元陆角柒分')
})
it('100010000.00 toBe 壹亿零壹万元', () => {
expect(numberToWords(100010000.00)).toBe('壹亿零壹万元整')
})
it('100010000.01 toBe 壹亿零壹万元壹分', () => {
expect(numberToWords(100010000.01)).toBe('壹亿零壹万元壹分')
})
})
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment