基于用户输入React JS的价格计算



我有一个函数,可以根据平方英尺和基本价格计算价格。

2000年代以后,每500平方英尺的价格就会上涨10%。2000平方英尺及以下的价格为149.99。

函数如下。。。

checkPrice = () => {
debugger;
let base_price = 149.99;
if(this.state.propertySqft > 2000){
let overage = this.state.propertySqft - 2000;
let percentage = Math.floor(overage % 500) * 10;
base_price += base_price * percentage;
this.setState({ totalPrice: base_price });
}
}

我遇到的问题是,如果平方英尺是一个整数,则percentage显示为"0",而math.ceil(overage % 500)似乎工作不正常。

例如。。。。如果我投入5001平方英尺,价格应该是149.99*60%,也就是239.98,但结果是164.98,因为percentage最终只为10,而不是60。

如果我输入5000平方英尺,percentage会显示为"0",这是我输入的任何整数作为平方英尺的情况。

有人知道我在这里做错了什么吗?或者为什么这没有按照我期望的方式进行?

模运算符用于获得到下一个较低倍数的距离,例如2006 % 500将是6,如500 * 4 + 6 = 2006。您想要除以,在这种情况下得到4:2006 / 500 = 4.00...,然后将其降为下一个整数。

此外,如果你把基本价格乘以10,你不会增加10%,而是增加1000%。您可能想要0.1(10/em>(。

我会把它写成:

const basePrice = 149.99;
const checkPrice = () => {
this.setState(({ propertySqft }) => { // asynchronous access to this.state is dangerous, use a callback!     
const percentage = Math.max(
0, // ensure that it only gets more 
Math.floor((propertySqft - 2000) / 500) * (10 / 100)
);
return { totalPrice: basePrice * (1 + percentage),  };
});
};

最新更新