React加密货币项目:不使用toFixed动态添加尾随零匹配精度
解决方案
先写一个专门的格式化函数,实现截断小数到指定精度+补尾随零的逻辑,完全避开toFixed的四舍五入问题:
// 格式化数字:截断到指定精度,不足补零 const formatBalanceWithTrailingZeros = (num, precision) => { // 把数字转成字符串,拆分整数和小数部分 const [integerPart, decimalPart = ''] = num.toString().split('.'); // 处理小数部分:截断到precision位,不足的补零 const processedDecimal = decimalPart.slice(0, precision).padEnd(precision, '0'); // 拼接结果,兼容精度为0的情况 return precision > 0 ? `${integerPart}.${processedDecimal}` : integerPart; };
再把这个函数集成到你的getInternalAssetBalance中,假设你需要从assetObj里取free或total作为余额值:
const getInternalAssetBalance = (selectedAsset, pairType, useFreeTotal = false) => { const exchangeInternalAccount = holdingsByAccount.find(account => account.exchange === 'REGULAR'); const assetObj = exchangeInternalAccount && exchangeInternalAccount.assets.find(item => item.name === selectedAsset); if (!assetObj) return '0.00000'; // 未找到资产时返回默认格式 // 根据参数选择对应的余额字段 const balance = useFreeTotal ? assetObj.total : assetObj.free; // 这里的精度可以根据需求调整,示例用5位 const precision = 5; return formatBalanceWithTrailingZeros(balance, precision); };
逻辑说明
- 转字符串拆分整数和小数,彻底避免
toFixed的四舍五入行为 slice(0, precision)直接截断超长的小数部分,不做任何舍入padEnd(precision, '0')自动补零到指定精度长度,比如原小数3位、精度5位时补两个零- 兼容精度为0的场景(此时不显示小数点和小数部分)
测试示例
- 输入
12.353、精度5 → 输出12.35300 - 输入
45.678901、精度5 → 输出45.67890(截断最后一位) - 输入
789、精度5 → 输出789.00000
内容的提问来源于stack exchange,提问作者Kimbo
相关产品推荐
相关产品推荐

