70

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?

Ry-
  • 218,210
  • 55
  • 464
  • 476
Eric
  • 2,201
  • 5
  • 29
  • 35

6 Answers6

135

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
Ry-
  • 218,210
  • 55
  • 464
  • 476
  • 9
    Math.floor() will give the wrong result for negative numbers. Consider mozey's answer below for better alternatives. – Jon Brooks Oct 04 '13 at 21:10
  • @JonBrooks: Thanks, but I recommended `parseInt` to begin with. Consider mozey’s answer for slow, complex alternatives. – Ry- Oct 05 '13 at 01:37
  • 2
    mozey's `trunc2` is actually the correct option, plus it uses integer comparison rather than string parsing which would make it much faster than `parseInt`, along with always returning the correct result. – BlinkyTop Aug 11 '14 at 06:29
  • @BlinkyTop: Eric talked about the `substr` function, so my first option talked about strings. I’m well aware of the problems of using `parseInt` on a number (see my comment on mozey’s answer, which is actually mostly wrong). – Ry- Aug 12 '14 at 01:02
  • 1
    Are you sure about `Math.trunc` being supported in IE 11? [MDN](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Math/trunc) says there is no IE support. I also tried it in IE 11 and got "Object doesn't support property or method 'trunc'". – Frank Tan Oct 27 '16 at 18:46
  • 1
    @FrankTan: Ah, sorry, I had meant Edge. Luckily, it’s easy to shim. – Ry- Oct 28 '16 at 02:16
18

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);
}
Community
  • 1
  • 1
BlinkyTop
  • 1,124
  • 3
  • 14
  • 19
  • For me Math.trunc(-2.2043642353916286e-15) returns zero. I have tested it in https://www.typescriptlang.org/play/ – Devid Sep 30 '17 at 10:09
14

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
  • 3,260
  • 4
  • 27
  • 55
  • 2
    I don't understand why this answer was downvoted. It is the only correct way! – BlinkyTop Aug 11 '14 at 06:24
  • @BlinkyTop Because `Math.trunc(x)` does exactly that – maganap Sep 03 '20 at 09:46
  • @magnap when this question was answered `Math.trunc(x)` was fairly new and not supported by all modern browsers at the time. For example, it would not work with Microsoft Edge at the time (Edge 12 released in 2015 and onward does support it) and IE even today does not support `Math.trunc(x)`. – Travis Pessetto Oct 07 '20 at 22:50
10

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.

mozey
  • 2,222
  • 2
  • 27
  • 34
  • `parseInt` and string replacement will return incorrect answers for numbers larger than 999999999999999900000. – Ry- Aug 10 '14 at 14:48
  • my take-away from this experience: unless performance is a huge issue, just use `parseInt` for simplicity, otherwise implement `trunc3()` – RozzA Jan 06 '17 at 19:26
1

Use Math.floor():

var f = 20.536;
var i = Math.floor(f);  // 20

http://jsfiddle.net/J4UVV/1/

gilly3
  • 87,962
  • 25
  • 144
  • 176
  • 2
    If you use a negative number say -20.536 then you will get the wrong result for truncation as it results in -21 http://jsfiddle.net/zL1v5e2k/ – Travis Pessetto Aug 12 '14 at 14:51
1

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
Asad Manzoor
  • 1,355
  • 15
  • 18