我在使用toFixed()函数时遇到困难。在下面的代码中,当我调用setState时,我试图将计算固定为两位小数,但是由于某种原因,我得到一个错误,提示toFixed() is not a function
我确保将tipPercent和小计都视为带有typeof()
的数字
this.setState({
subtotal,
tip: (this.state.tipPercent * subtotal).toFixed(2),
tax: (0.07 * subtotal).toFixed(2),
fee: 1,
});
这是总的代码块:
calculateTotal = () => {
var total = 0;
var subtotal = 0;
// calculate subtotal
Object.keys(this.state.bill.items).map((item) => {
subtotal +=
this.state.bill.items[item].price *
this.state.bill.items[item].quantity;
});
// calculate tax/tip
if (subtotal !== 0) {
this.setState({
subtotal,
tip: (this.state.tipPercent * subtotal).toFixed(2),
tax: (0.07 * subtotal).toFixed(2),
fee: 1,
});
} else {
this.setState({
subtotal,
tip: 0,
tax: 0,
});
}
total = subtotal + this.state.tax + this.state.tip + this.state.fee;
this.setState({ total: total, loading: false });
};
this.state.bill.items
如下所示:
Array [
Object {
"item": "Sip of Sunshine",
"price": 6.5,
"quantity": 4,
},
Object {
"item": "Sip of Sunshine",
"price": 6.5,
"quantity": 3,
},
Object {
"item": "Bud Light",
"price": 2.75,
"quantity": 2,
},
]
答案 0 :(得分:-1)
我能够通过使用Math.round()
操作并将整个方程式乘以100,然后除以100来解决此问题,因为数学方法自然会将JavaScript排除在很多地方
由于toFixed()
返回一个字符串,因此无法将下面的状态设置为适当的数字值。 Math.round()
通过始终将数字四舍五入到小数点后两位来解决此问题。
这是calculateTotal()
函数的更新版本:
calculateTotal = () => {
var subtotal = 0;
// calculate subtotal
Object.keys(this.state.bill.items).forEach((item) => {
subtotal +=
this.state.bill.items[item].price *
this.state.bill.items[item].quantity;
});
if (subtotal !== 0) {
this.setState({
subtotal,
tip: Math.round(this.state.tipPercent * subtotal * 100) / 100,
tax: Math.round(0.07 * subtotal * 100) / 100,
fee: 1,
});
this.setState({
total: subtotal + this.state.tax + this.state.tip + this.state.fee,
loading: false,
});
}
};