我在使用 toFixed() 函数时遇到困难。在下面的代码中,当我调用 setState 时,我试图将计算固定为两位小数,但由于某种原因,我收到一条错误消息toFixed() is not a function
我确保 tipPercent 和 subtotal 都被认为是数字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,
},
]
桃花长相依
相关分类