如何将数字四舍五入到 500

use*_*391 1 javascript reactjs react-native

我有一个文本输入,它只接受可被 500 个示例 1000、1500、2000、2500 3000 等整除的任何数字。如果用户写 12263 它应该四舍五入到 12000 如果用户写 12789 它应该四舍五入到 12500

我有这个代码,但它根本不起作用,在某些数字上工作正常,但在其他数字上它只是转到最大数字

vPayrollBureauMaxOffer:是可以接受的最大数字我从 api vPayrollAmount:是用户在 textinput 中写入的金额 3000 是可接受的最小值,如果用户写的数字小于 3000,它应该更改为 3000

这是我的代码

const validatePayroll = () => {
    if(vPayrollAmount <= 3000){
      return setvPayrollAmount((3000));
    }
    if(vPayrollAmount >= vPayrollBureauMaxOffer){
      return setvPayrollAmount(vPayrollBureauMaxOffer.toString().replace(/\B(?=(\d{3})+(?!\d))/g, ','));
    }
    if((vPayrollAmount >= 3000) && (vPayrollAmount <= vPayrollBureauMaxOffer)){
      return setvPayrollAmount(Math.floor(vPayrollAmount / 500.0) * 500.0);
    }
  };  

<TextInput
   style={styles.inputs}
   placeholder={`${vPayrollAmount.toString().replace(/\B(?=(\d{3})+(?!\d))/g, ',')}`}
   placeholderTextColor={theme.SECONDARY_TEXT_COLOR}
   keyboardType={'numeric'}
   underlineColorAndroid="transparent"
   autoCorrect={false}
   autoCapitalize="characters"
   value={vPayrollAmount}
   onBlur={() => validatePayroll(vPayrollAmount)}
   onChangeText={setvPayrollAmount}
   />
Run Code Online (Sandbox Code Playgroud)

T.J*_*der 5

通常要做的事情是除以倍数(在您的情况下为 500),将结果四舍五入,然后乘以倍数:

const values = [12263, 12789];
for (const value of values) {
    const result = Math.round(value / 500) * 500;
    console.log(`${value} => ${result}`);
}
Run Code Online (Sandbox Code Playgroud)

但这确实是标准的四舍五入,输入 12,263 时为 12,500,因为这更接近于 12,500 而不是 12,000(237 远对 263 远)。

您可以Math.floor改为使用始终向下舍入到最接近的 500 倍数以获取您在问题中引用的值:

const values = [12263, 12789];
for (const value of values) {
    const result = Math.floor(value / 500) * 500;
    console.log(`${value} => ${result}`);
}
Run Code Online (Sandbox Code Playgroud)

(同样,如果你总是想走另一条路,那就是Math.ceil。)

请注意,如果处理负数,您将需要反转Math.floorMath.ceil处理负数,因为它们总是分别下降上升,而不是朝向 0。例如,Math.floor(-5.2)is -6