Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
605 views
in Technique[技术] by (71.8m points)

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

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

EDIT:

if(value<1000){
  value = 1000;
}else{
  value = Math.round(value/1000)*1000;
}
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...