[javascript] How can I remove the decimal part from JavaScript number?

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

How can I do this?

This question is related to javascript

The answer is


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.


You could also do

parseInt(a/b)

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}`;
}

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.


For Example:

var x = 9.656;
x.toFixed(0);           // returns 10
x.toFixed(2);           // returns 9.66
x.toFixed(4);           // returns 9.6560
x.toFixed(6);           // returns 9.656000 

or

parseInt("10");         // returns 10
parseInt("10.33");      // returns 10
parseInt("10 20 30");   // returns 10
parseInt("10 years");   // returns 10
parseInt("years 10");   // returns NaN  

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];

u can also show a certain number of digit after decimal point(here 2 digits) using following code :

_x000D_
_x000D_
var num = (15.46974).toFixed(2)_x000D_
console.log(num) // 15.47_x000D_
console.log(typeof num) // string
_x000D_
_x000D_
_x000D_


Here is the compressive in detailed explanation with the help of above 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


You can also use bitwise operators to truncate the decimal.

e.g.

var 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:

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 (~~)


Use Math.round() function.

Math.round(65.98) // will return 66 
Math.round(65.28) // will return 65

Use Math.round().

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


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

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.


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>