Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Truncate/round whole number in JavaScript?

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?

like image 408
Eric Avatar asked Apr 14 '12 00:04

Eric


People also ask

How do you round a whole number in JavaScript?

round() The Math. round() function returns the value of a number rounded to the nearest integer.

How do you truncate a value in JavaScript?

In JavaScript, trunc() is a function that is used to return the integer portion of a number. It truncates the number and removes all fractional digits. Because the trunc() function is a static function of the Math object, it must be invoked through the placeholder object called Math.

How do you truncate a whole number?

To truncate a number, we miss off digits past a certain point in the number, filling-in zeros if necessary to make the truncated number approximately the same size as the original number. To truncate a number to 1 decimal place, miss off all the digits after the first decimal place.

How do you round to the lowest whole number in JavaScript?

The Math. floor() method rounds a number DOWN to the nearest integer.


2 Answers

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 
like image 86
Ry- Avatar answered Oct 13 '22 08:10

Ry-


Travis Pessetto's answer along with mozey's trunc2 function were the only correct answers, considering how JavaScript represents very small or very large floating point numbers in scientific notation.

For example, parseInt(-2.2043642353916286e-15) will not correctly parse that input. Instead of returning 0 it will return -2.

This is the correct (and imho the least insane) way to do it:

function truncate(number) {     return number > 0          ? Math.floor(number)          : Math.ceil(number); } 
like image 37
BlinkyTop Avatar answered Oct 13 '22 09:10

BlinkyTop