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?
This question is related to
javascript
decimal
rounding
Convert the number to a string and throw away everything after the decimal.
trunc = function(n) { return Number(String(n).replace(/\..*/, "")) }
trunc(-1.5) === -1
trunc(1.5) === 1
Edit 2013-07-10
As pointed out by minitech and on second thought the string method does seem a bit excessive. So comparing the various methods listed here and elsewhere:
function trunc1(n){ return parseInt(n, 10); }
function trunc2(n){ return n - n % 1; }
function trunc3(n) { return Math[n > 0 ? "floor" : "ceil"](n); }
function trunc4(n) { return Number(String(n).replace(/\..*/, "")); }
function getRandomNumber() { return Math.random() * 10; }
function test(func, desc) {
var t1, t2;
var ave = 0;
for (var k = 0; k < 10; k++) {
t1 = new Date().getTime();
for (var i = 0; i < 1000000; i++) {
window[func](getRandomNumber());
}
t2 = new Date().getTime();
ave += t2 - t1;
}
console.info(desc + " => " + (ave / 10));
}
test("trunc1", "parseInt");
test("trunc2", "mod");
test("trunc3", "Math");
test("trunc4", "String");
The results, which may vary based on the hardware, are as follows:
parseInt => 258.7
mod => 246.2
Math => 243.8
String => 1373.1
The Math.floor / ceil method being marginally faster than parseInt and mod. String does perform poorly compared to the other methods.
I'll add my solution here. We can use floor when values are above 0 and ceil when they are less than zero:
function truncateToInt(x)
{
if(x > 0)
{
return Math.floor(x);
}
else
{
return Math.ceil(x);
}
}
Then:
y = truncateToInt(2.9999); // results in 2
y = truncateToInt(-3.118); //results in -3
Notice: This answer was written when Math.trunc(x)
was fairly new and not supported by a lot of browsers. Today, modern browsers support Math.trunc(x)
.
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);
}
Math.trunc() function removes all the fractional digits.
For positive number it behaves exactly the same as Math.floor():
console.log(Math.trunc(89.13349)); // output is 89
For negative numbers it behaves same as Math.ceil():
console.log(Math.trunc(-89.13349)); //output is -89
Source: Stackoverflow.com