Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Round a number to nearest thousand [duplicate]

Tags:

javascript

I know it is possible to round a number with Math.floor or Math.round with jquery but i need to round a non decimal number.

var num = 89250;
var round = Math.round(num);

Obviously it's not working, googled but no success, is it possible?

for example i need to round the number below:

89250 => 89000

i did a trick but don't want a dirty work and also decimal number.

var num = 89250;
var round = Math.round(+num.toLocaleString('en').replace(',', '.'));
var total = round.toFixed(3);
like image 961
Pedram Avatar asked Oct 26 '25 16:10

Pedram


1 Answers

First divide your number by 1000, then round, and multiply again:

var num = 89250;
var rounded = Math.round(num / 1000) * 1000;

If you want a different tie-breaking -- rounding ties down instead of up -- then apply the negation operator to the number before and after the rounding. Compare the difference in the output:

var num = 89500;
var rounded = -Math.round(-num / 1000) * 1000;
console.log('rounding tie down: ', rounded);  // 89000


var num = 89500;
var rounded = Math.round(num / 1000) * 1000;
console.log('rounding tie up: ', rounded);  // 90000
like image 195
trincot Avatar answered Oct 29 '25 06:10

trincot