Get decimal portion of a number with JavaScript

Get decimal portion of a number with JavaScript

I have float numbers like 3.2 and 1.6.
I need to separate the number into the integer and decimal part. For example, a value of 3.2 would be split into two numbers, i.e. 3 and 0.2
Getting the integer portion is easy:
n = Math.floor(n);

But I am having trouble getting the decimal portion.
I have tried this:
remainer = n % 2; //obtem a parte decimal do rating

But it does not always work correctly.
The previous code has the following output:
n = 3.1 => remainer = 1.1

What I am missing here?

Solutions/Answers:

Solution 1:

Use 1, not 2.

js> 2.3 % 1
0.2999999999999998

Solution 2:

var decimal = n - Math.floor(n)

Although this won’t work for minus numbers so we might have to do

n = Math.abs(n); // Change to positive
var decimal = n - Math.floor(n)

Solution 3:

You could convert to string, right?

n = (n + "").split(".");

Solution 4:

How is 0.2999999999999998 an acceptable answer? If I were the asker I would want an answer of .3. What we have here is false precision, and my experiments with floor, %, etc indicate that Javascript is fond of false precision for these operations. So I think the answers that are using conversion to string are on the right track.

Related:  Using map() on an iterator

I would do this:

var decPart = (n+"").split(".")[1];

Specifically, I was using 100233.1 and I wanted the answer “.1”.

Solution 5:

A simple way of doing it is:

var x = 3.2;
var decimals = x - Math.floor(x);
console.log(decimals); //Returns 0.20000000000000018

Unfortunately, that doesn’t return the exact value. However, that is easily fixed:

var x = 3.2;
var decimals = x - Math.floor(x);
console.log(decimals.toFixed(1)); //Returns 0.2

You can use this if you don’t know the number of decimal places:

var x = 3.2;
var decimals = x - Math.floor(x);

var decimalPlaces = x.toString().split('.')[1].length;
decimals = decimals.toFixed(decimalPlaces);

console.log(decimals); //Returns 0.2

Solution 6:

Here’s how I do it, which I think is the most straightforward way to do it:

var x = 3.2;
int_part = Math.trunc(x); // returns 3
float_part = Number((x-int_part).toFixed(2)); // return 0.2