我对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,
},
]发布于 2020-10-20 19:33:52
我能够通过使用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,
});
}
};https://stackoverflow.com/questions/64449147
复制相似问题