Truncate/round whole number in JavaScript?

Eric picture Eric · Apr 14, 2012 · Viewed 107.5k times · Source

For a script I'm writing, I need display a number that has been rounded, but not the decimal or anything past it. I've gotten down to rounding it to the third place, but I'm not sure how to go about just dropping the decimal and everything past it, as it doesn't seem like JavaScript has a substr function like PHP does.

Any recommendations?

Answer

Ry- picture Ry- · Apr 14, 2012

If you have a string, parse it as an integer:

var num = '20.536';
var result = parseInt(num, 10);  // 20

If you have a number, ECMAScript 6 offers Math.trunc for completely consistent truncation, already available in Firefox 24+ and Edge:

var num = -2147483649.536;
var result = Math.trunc(num);  // -2147483649

If you can’t rely on that and will always have a positive number, you can of course just use Math.floor:

var num = 20.536;
var result = Math.floor(num);  // 20

And finally, if you have a number in [−2147483648, 2147483647], you can truncate to 32 bits using any bitwise operator. | 0 is common, and >>> 0 can be used to obtain an unsigned 32-bit integer:

var num = -20.536;
var result = num | 0;  // -20