Javascript 四舍五入到最接近的千,根据数字向上或向下

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/26906657/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-22 23:30:47  来源:igfitidea点击:

Round number to nearest thousand, up or down depending on the number

javascript

提问by Gustavo Sanchez

I want to round up a number to the nearest thousand, at the moment I'm using this:

我想将一个数字四舍五入到最接近的千位,目前我正在使用这个:

Math.ceil(value/1000)*1000;

But this goes always up, if I type 1001 it will go to 2000, I want to go up or down depeding on the number, for example 1001 goes to 1000 or 1400 goes to 1000 but 1500 goes to 2000

但这总是上升,如果我输入 1001 它会到 2000,我想根据数字上升或下降,例如 1001 到 1000 或 1400 到 1000 但 1500 到 2000

EDIT:

编辑:

if(value<1000){
  value = 1000;
}else{
  value = Math.round(value/1000)*1000;
}

回答by simonzack

This will do what you want:

这将执行您想要的操作:

Math.round(value/1000)*1000

examples:

例子:

Math.round(1001/1000)*1000
1000
Math.round(1004/1000)*1000
1000
Math.round(1500/1000)*1000
2000

回答by Max Bumaye

var rest = number % 1000; 
if(rest > 500) 
{ number = number - rest + 1000; } 
  else 
{ number = number - rest; } 

maybe a bit straight forward.. but this does it

也许有点直截了当..但这做到了

EDIT: of course this should go in some kind of myRound() function

编辑:当然这应该在某种 myRound() 函数中

I read about the problem with your 1 needing to round up to 1000. this behaviour is controverse compared to the rest - so you will have to add something like:

我读到你的 1 需要四舍五入到 1000 的问题。与其他行为相比,这种行为是有争议的 - 所以你必须添加如下内容:

if(number < 1000)
{  number = 1000; return number; }

ontop of your function;

在您的功能之上;

回答by sam

By using ES3 Number method, it performs a rounding if no decimal place defined.

通过使用 ES3 Number 方法,如果没有定义小数位,它会执行四舍五入。

(value / 1000).toFixed() * 1000







原来的答案是:

(value / 1000).toFixed(3) * 1000;

Yet this is incorrect, due to the value will return the exact original number, instead of affecting the ceil/floor on the value.

然而这是不正确的,因为该值将返回准确的原始数字,而不是影响该值的 ceil/floor。