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?
round() The Math. round() function returns the value of a number rounded to the nearest integer.
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.
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.
The Math. floor() method rounds a number DOWN to the nearest integer.
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
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); }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With