336

I have the results of a division and I wish to discard the decimal portion of the resultant number.

How can I do this?

General Grievance
  • 4,555
  • 31
  • 31
  • 45
JacobTheDev
  • 17,318
  • 25
  • 95
  • 158

14 Answers14

578

You could use...

...dependent on how you wanted to remove the decimal.

Math.trunc() isn't supported on all platforms yet (namely IE), but you could easily use a polyfill in the meantime.

Another method of truncating the fractional portion with excellent platform support is by using a bitwise operator (.e.g |0). The side-effect of using a bitwise operator on a number is it will treat its operand as a signed 32bit integer, therefore removing the fractional component. Keep in mind this will also mangle numbers larger than 32 bits.


You may also be talking about the inaccuracy of decimal rounding with floating point arithmetic.

Required Reading - What Every Computer Scientist Should Know About Floating-Point Arithmetic.

alex
  • 479,566
  • 201
  • 878
  • 984
  • 43
    Keep in mind that `Math.floor()` will **increase** numerical value when number is **negative**. Thus `Math.floor(-1.2) -> -2` whilst `Math.floor(1.2) -> 1`. `parseInt(-1.2) -> -1` (_as mentioned by @FloydPink_) will discard decimal part as expected for both _positive_ and _negative_ numbers. – Paul T. Rawkeen Nov 06 '14 at 09:53
  • 2
    the following shows this answer is unstable:```> (2.305*100)|0 > 230 > (2.3*100)|0 > 229``` – Yin Feb 18 '16 at 08:28
  • 4
    @Jake The result of `2.3*100` in javascript is `229.99999999999997`, so it seems the bitwise operator is doing its job correctly in your example. – Chad von Nau Apr 01 '16 at 00:28
94

You can also use bitwise operators to truncate the decimal.

e.g.

let x = 9 / 2;
console.log(x); // 4.5

x = ~~x;
console.log(x); // 4

x = -3.7
console.log(~~x) // -3
console.log(x | 0) // -3
console.log(x << 0) // -3

Bitwise operations are considerably more efficient than the Math functions. The double not bitwise operator also seems to slightly outperform the x | 0 and x << 0 bitwise operations by a negligible amount.

// 952 milliseconds
for (var i = 0; i < 1000000; i++) {
    (i * 0.5) | 0;
}

// 1150 milliseconds
for (var i = 0; i < 1000000; i++) {
    (i * 0.5) << 0;
}

// 1284 milliseconds
for (var i = 0; i < 1000000; i++) {
    Math.trunc(i * 0.5);
}

// 939 milliseconds
for (var i = 0; i < 1000000; i++) {
    ~~(i * 0.5);
}

Also worth noting is that the bitwise not operator takes precedence over arithmetic operations, so you may need to surround calculations with parentheses to have the intended result:

const x = -3.7

console.log(~~x * 2) // -6
console.log(x * 2 | 0) // -7
console.log(x * 2 << 0) // -7

console.log(~~(x * 2)) // -7
console.log(x * 2 | 0) // -7
console.log(x * 2 << 0) // -7

More info about the double bitwise not operator can be found at Double bitwise NOT (~~)

You also should ensure that your integer will not need more than 32-bits to represent:

const a = 0x100000000 + 0.1; // 4294967296.1
console.log(Math.trunc(a)); // 4294967296
console.log(~~a); // 0
General Grievance
  • 4,555
  • 31
  • 31
  • 45
Braden Steffaniak
  • 2,053
  • 3
  • 25
  • 37
  • 6
    Might be marginally efficient. But, i would suggest 'Math' functions, as its more readable. – Ashish Joseph Feb 26 '17 at 15:17
  • 1
    If you do this, make sure you wrap your bitwise operation in a function with a reasonable name. Otherwise get ready for your co-workers to crucify you. – Krisztián Balla Jan 07 '21 at 14:43
  • @KrisztiánBalla Part of the reason that Math methods are slower in the above tests is the function call overhead. Wrapping the `~~(x)` in a function will cause a similar slowdown, and then you may as well just call the `Math` methods. – General Grievance May 25 '23 at 13:54
37

You could also do

parseInt(a/b)
Hari Pachuveetil
  • 10,294
  • 3
  • 45
  • 68
  • 19
    Note that `parseInt` won't work reliably for large numbers, because it works by first converting its argument to a string, and for large numbers the result will use exponential notation. For example: `var n = 22222222222222222222222; parseInt(n);` will return `2`, because `n.toString()` returns `2.2222222222222223e+22`. –  Oct 27 '15 at 11:00
  • 4
    It's also not using `parseInt()` for its purpose, which is to take a number in a string and return a `Number`. – alex Jan 18 '16 at 16:01
35

You can also show a certain number of digit after decimal point (here 2 digits) using toFixed, which will return a string representation:

var num = (15.46974).toFixed(2)
console.log(num) // 15.47
console.log(typeof num) // string
General Grievance
  • 4,555
  • 31
  • 31
  • 45
Mahdi ghafoorian
  • 1,147
  • 10
  • 8
  • 3
    How is this an answer as OP asking to remove the decimal part – Isaac Jun 24 '18 at 13:25
  • 4
    Although it returns a string, you can just use the Number() method to correct that.. Number((15.46974).toFixed(2)) – iPzard Mar 31 '19 at 18:22
  • LoLs! `console.log(typeof num) // string` Ummm, I think this is the JS equivalent of an oxymoron. – JΛYDΞV Jul 31 '22 at 05:23
  • 1
    `toFixed` would never be introduced to JavaScript today. It was added to the language back in a time when there was hardly a difference between a string and a number, today, types matter, as they should. Use Math.trunc() if you care about good code, unless u need a specific amount of decimal place (which your probably in a CS class if that is the case) use `Number(x.toFixed(digits))`, or have a very specific need for converting a number to a string at a certain amount of decimal places, which probably isn't all that rare, but for algorithmic scripting, don't use toFixed, use `Math.trunc`. – JΛYDΞV Jul 31 '22 at 05:31
18

Use Math.round() function.

Math.round(65.98) // will return 66 
Math.round(65.28) // will return 65
Toby Allen
  • 10,997
  • 11
  • 73
  • 124
Navdeep Singh
  • 403
  • 4
  • 5
  • 1
    `Math.round` doesn't actually answer the question though. The question was how to disregard the decimal portion of the number. In the example shown by the answer here, the OP would want to return 65 in both instances. `Math.round` will return 66 or 65 (as stated above). – Peter Nixey Sep 27 '20 at 18:32
12

Use Math.round().

(Alex's answer is better; I made an assumption :)

Dave Newton
  • 158,873
  • 26
  • 254
  • 302
9

With ES2015, Math.trunc() is available.

Math.trunc(2.3)                       // 2
Math.trunc(-2.3)                      // -2
Math.trunc(22222222222222222222222.3) // 2.2222222222222223e+22
Math.trunc("2.3")                     // 2
Math.trunc("two")                     // NaN
Math.trunc(NaN)                       // NaN

It's not supported in IE11 or below, but does work in Edge and every other modern browser.

Chad von Nau
  • 4,316
  • 1
  • 23
  • 34
  • 2
    Know of any variations that allow to truncate to X decimal places? Would it be naive to think that `Math.trunc(value * Math.pow(10,x)) / Math.pow(10,x)` would work? – jamiebarrow Apr 21 '16 at 15:19
  • 2
    Hey Jamie, it looks like that would work for most cases, but it's susceptible to floating point gotchas. e.g. `value = 2.3` and `x = 2` will return `2.29`. I don't have a better suggestion. – Chad von Nau Apr 23 '16 at 19:42
  • This to me sounds like the right answer. No rounding upper or lower. No problems with negative numbers. Just discard the decimal. As the question asked for. – Enrique Moreno Tent Nov 22 '16 at 09:39
7

Here is the compressive in detailed explanation with the help of previous posts:

1. Math.trunc() : It is used to remove those digits which are followed by dot. It converts implicitly. But, not supported in IE.

Example:

Math.trunc(10.5) // 10
Math.trunc(-10.5) // -10    

Other Alternative way: Use of bitwise not operator:

Example:

x= 5.5
~~x // 5

2. Math.floor() : It is used to give the minimum integer value posiible. It is supported in all browsers.

Example:

Math.floor(10.5) // 10
Math.floor(-10.5) // -11

3. Math.ceil() : It is used to give the highest integer value possible. It is supported in all browsers.

Example:

Math.ceil(10.5) // 11
Math.ceil(-10.5) // -10

4. Math.round() : It is rounded to the nearest integer. It is supported in all browsers.

Example:

Math.round(10.5) // 11
Math.round(-10.5)// -10
Math.round(10.49) // 10
Math.round(-10.51) // -11
General Grievance
  • 4,555
  • 31
  • 31
  • 45
sreepurna
  • 1,562
  • 2
  • 17
  • 32
3

You can use .toFixed(0) to remove complete decimal part or provide the number in arguments upto which you want decimal to be truncated.

Note: toFixed will convert the number to string.

Nikhil Kamani
  • 850
  • 9
  • 12
2

toFixed will behave like round.

For a floor like behavior use %:

var num = 3.834234;
var floored_num = num - (num % 1); // floored_num will be 3
Shahar Hajdu
  • 315
  • 2
  • 4
  • 3
    Why do you feel this is better than using Math.floor? Your solution seems unnecessarily complex, and slow. I do not know how Math.floor works, but I expect it to be a lot more optimized. Also, I wonder if your solution might give suffer from floating point rounding errors. – Hans Roerdinkholder Feb 10 '16 at 13:57
2

If you don't care about rouding, just convert the number to a string, then remove everything after the period including the period. This works whether there is a decimal or not.

const sEpoch = ((+new Date()) / 1000).toString();
const formattedEpoch = sEpoch.split('.')[0];
Post Impatica
  • 14,999
  • 9
  • 67
  • 78
1

This is for those who want to prevent users to enter decimal numbers

<input id="myInput" onkeyup="doSomething()" type="number" />

<script>
    function doSomething() {

        var intNum = $('#myInput').val();

        if (!Number.isInteger(intNum)) {
            intNum = Math.round(intNum);
        }

        console.log(intNum);
    }
</script>
Masoud Darvishian
  • 3,754
  • 4
  • 33
  • 41
0

For an ES6 implementation, use something like the following:

const millisToMinutesAndSeconds = (millis) => {
  const minutes = Math.floor(millis / 60000);
  const seconds = ((millis % 60000) / 1000).toFixed(0);
  return `${minutes}:${seconds < 10 ? '0' : ''}${seconds}`;
}
Jared
  • 631
  • 1
  • 7
  • 19
0

In this examples I use Number.toFixed and Math.trunc methods:

const num = 1.234

Number(num.toFixed(0)); // Returns 1
Number(num.toFixed(2)); // Returns 1.23

Math.trunc(num); // Returns 1

The toFixed() method formats a number using fixed-point notation.
The Math.trunc() static method returns the integer part of a number by removing any fractional digits.

I.sh.
  • 252
  • 3
  • 13