JavaScript使用toFixed保留一位小数的踩坑记录:TypeError: xxx.toFixed is not a function

59 篇文章 ¥19.90 ¥99.00

JavaScript的toFixed函数是用于将一个数字格式化为指定的小数位数的字符串。其语法如下:

numObj.toFixed([digits])

其中,numObj是需要格式化的数字,digits是保留的小数位数。digits参数是一个可选参数,默认值为0,表示不保留小数位。  

计算后需要保留一位小数,于是使用toFixed方法:

child.order = (child.order + offset).toFixed(1);

然而第一次执行正确,第二次执行时,提示

TypeError:  (child.order + offset).toFixed is not a function

原因:

toFixed()的返回值是String,不是Number

这就导致执行第一次后,child.order的类型变成了String,这样第二次执行toFixed的时候出错

这个错误: ``` TypeError: this.originalHours.toFixed is not a function ``` 表示你调用 `.toFixed()` 方法时,`this.originalHours` **不是一个数字(number)类型**,而是一个字符串、`null` 或者 `undefined`。 --- ### ❓ 为什么会报这个错? `.toFixed(n)` 是 JavaScript 中 `Number` 类型的方法,只能用于数字类型。如果你尝试在一个非数字类型的变量上调用它,就会报错。 --- ### ✅ 示例说明: ```js let a = 1.2345 a.toFixed(2) // 正确:输出 "1.23" let b = '1.2345' b.toFixed(2) // ❌ 报错:TypeError: b.toFixed is not a function let c = null c.toFixed(2) // ❌ 报错:TypeError: Cannot read property 'toFixed' of null let d = undefined d.toFixed(2) // ❌ 报错:TypeError: Cannot read property 'toFixed' of undefined ``` --- ### ✅ 如何修复? 你需要确保 `this.originalHours` 是一个数字类型(`typeof this.originalHours === 'number'`)。 --- ### ✅ 修改后的验证方法: ```javascript validateHourReduction() { // 先确保 originalHours 是 number 类型 const max = parseFloat(this.originalHours); // 转换为数字 if (isNaN(max)) { this.hourReduction = 0; this.$message.warning('原始免费时长无效'); return; } // 判断当前输入是否是有效数字 if (typeof this.hourReduction !== 'number' || isNaN(this.hourReduction)) { this.hourReduction = 0; this.$message.warning('请输入有效的数字'); return; } // 限制最大值和最小值 if (this.hourReduction > max) { this.hourReduction = parseFloat(max.toFixed(2)); this.$message.warning('减免时长不能超过原始免费时长'); } else if (this.hourReduction < 0) { this.hourReduction = 0; this.$message.warning('减免时长不能为负数'); } } ``` --- ### ✅ 更进一步的建议:在赋值前确保类型正确 如果你是从接口获取的 `originalHours`,建议在赋值前进行类型转换: ```javascript this.originalHours = parseFloat(data.delayInfo?.duration || 0); ``` 这样可以确保它始终是 `number` 类型。 --- ### ✅ 示例:确保原始数据是数字 ```js data() { return { originalHours: 0, // 默认初始化为数字 hourReduction: 0, } } ``` --- ### ✅ 总结错误原因: | 原因 | 说明 | |------|------| | `originalHours` 是字符串 | 例如 `'2.5'`,不能直接调用 `.toFixed()` | | `originalHours` 是 `null` 或 `undefined` | 无法调用 `.toFixed()` | | 数据未正确初始化或接口返回异常 | 导致变量不是 number 类型 | --- ### ✅ 相关问题:
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值