You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何实现将任意数值始终向下取整至1000的倍数?

如何将数值向下取整到1000的倍数?

你当前用的Math.round()是四舍五入逻辑,这就是为什么22745会被处理成23000——它把22.745四舍五入成了23。而你需要的是向下取整(不管小数部分是多少,直接舍去,保留整数位对应的1000倍数),用Math.floor()就能满足需求:

var myValue = 22745;
Math.floor(myValue / 1000) * 1000; // 输出22000,符合预期

验证你给出的所有示例:

console.log(Math.floor(6700 / 1000) * 1000);    // 6000
console.log(Math.floor(17500 / 1000) * 1000);   // 17000
console.log(Math.floor(356242 / 1000) * 1000);  // 350000
console.log(Math.floor(600 / 1000) * 1000);     // 0

补充说明:如果处理负数,Math.floor()依然遵循向下取整逻辑,比如Math.floor(-22745 / 1000) * 1000会得到-23000,这也是数学意义上的向下取整结果。

内容的提问来源于stack exchange,提问作者Mar1009

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.18 05:20:26