React.js数字转单词功能故障:小数部分显示undefined
数字转单词功能问题修复
问题详情
- 输入:118.65
- 实际输出:one hundred undefined rupees only
- 期望输出:one hundred eighteen Rupees and sixty five paisa only
问题根源
- 小数索引导致undefined:处理带小数的数字时,
number保留了小数部分,进入else if (number >= 10)分支时,number - 10得到小数(如18.65-10=8.65),用该小数作为teens数组索引会返回undefined。 - 小数部分丢失:递归和取余操作会修改原始数字,导致后续无法正确提取小数部分。
- 小数部分未转单词:代码直接拼接小数数字,未将其转换为对应英文单词。
修复后的代码
function App() { return <Textword grandtotalAmount={118.65} />; } function Textword({ grandtotalAmount }) { // 专门处理整数转单词 const convertIntegerToWords = (num) => { const units = [ "", "One", "Two", "Three", "Four", "Five", "Six", "Seven", "Eight", "Nine" ]; const tens = [ "", "Ten", "Twenty", "Thirty", "Forty", "Fifty", "Sixty", "Seventy", "Eighty", "Ninety" ]; const teens = [ "Ten", "Eleven", "Twelve", "Thirteen", "Fourteen", "Fifteen", "Sixteen", "Seventeen", "Eighteen", "Nineteen" ]; const crore = "Crore"; const lakh = "Lakh"; const arab = "Arab"; if (num === 0) return ""; let words = ""; if (num >= 1000000000) { words += convertIntegerToWords(Math.floor(num / 1000000000)) + " " + arab + " "; num %= 1000000000; } if (num >= 10000000) { words += convertIntegerToWords(Math.floor(num / 10000000)) + " " + crore + " "; num %= 10000000; } if (num >= 100000) { words += convertIntegerToWords(Math.floor(num / 100000)) + " " + lakh + " "; num %= 100000; } if (num >= 1000) { words += convertIntegerToWords(Math.floor(num / 1000)) + " Thousand "; num %= 1000; } if (num >= 100) { words += convertIntegerToWords(Math.floor(num / 100)) + " Hundred "; num %= 100; } if (num >= 20) { words += tens[Math.floor(num / 10)] + " "; num %= 10; } else if (num >= 10) { words += teens[num - 10] + " "; num = 0; } if (num > 0) { words += units[num] + " "; } return words.trim(); }; const convertNumberToWords = (number) => { const currency = "Rupees"; const paisa = "Paisa"; // 拆分整数与小数部分 const integerPart = Math.floor(number); const decimalPart = Math.round((number - integerPart) * 100); let words = ""; // 处理整数部分 if (integerPart === 0) { words += "Zero " + currency; } else { words += convertIntegerToWords(integerPart) + " " + currency; } // 处理小数部分 if (decimalPart > 0) { const paisaWords = convertIntegerToWords(decimalPart); words += " and " + paisaWords + " " + paisa + " only"; } else { words += " only"; } return words.trim(); }; let amountWord = convertNumberToWords(grandtotalAmount); return <React.Fragment>{amountWord}</React.Fragment>; } ReactDOM .createRoot(document.getElementById("root")) .render(<App />);
<div id="root"></div> <script src="https://cdnjs.cloudflare.com/ajax/libs/react/18.2.0/umd/react.development.js"></script> <script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/18.2.0/umd/react-dom.development.js"></script>
修复说明
- 拆分处理整数与小数:将原始数字拆分为两部分分别处理,避免递归操作破坏小数信息。
- 独立整数转单词逻辑:创建
convertIntegerToWords函数专门处理整数,确保所有操作的数字都是整数,消除小数索引导致的undefined问题。 - 小数部分转单词:复用整数转单词函数处理小数部分,实现完整的单词转换。
- 统一输出格式:调整"only"的位置,使输出与期望结果一致。
内容的提问来源于stack exchange,提问作者user 1997
相关产品推荐
相关产品推荐

