import React from 'react';
class AmountInWords extends React.Component {
render() {
const { amount } = this.props;
// 处理边界和非数值情况
if (isNaN(amount) || amount === Infinity || amount === -Infinity) {
return <span>{amount}</span>;
}
if (amount === 0) {
return <span>零元整</span>;
}
let nums = amount.toFixed(2).split('.');
let result = '';
// 将整数部分转为中文数字
let integerNum = parseInt(nums[0]);
if (integerNum > 0) {
let parts = [];
let integers = integerNum.toString().split('').map(Number);
for (let i = 0; i < integers.length; i++) {
let digit = integers[i];
let unit = ['', '拾', '佰', '仟'][integers.length - i - 1];
let nextDigit = integers[i + 1];
// 处理连续的零位
if (digit === 0 && nextDigit === 0) {
continue;
}
// 处理零数位
if (digit === 0) {
parts.push('零');
continue;
}
parts.push('零一二三四五六七八九'.charAt(digit) + unit);
}
result = parts.join('');
} else {
result = '零';
}
// 拼接小数部分
if (nums[1] && nums[1] !== '00') {
let decimalNum = parseInt(nums[1]);
let decimals = '零一二三四五六七八九'.charAt(decimalNum / 10) + '角' + '零一二三四五六七八九'.charAt(decimalNum % 10) + '分';
result += '元' + decimals;
} else {
result += '元整';
}
// 处理负数
if (amount < 0) {
result = '负' + result;
}
return <span>{result}</span>;
}
}
export default AmountInWords;
<AmountInChinese amount={1234567.89} />