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?
js> 2.3 % 1 0.2999999999999998
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)
You could convert to string, right?
n = (n + "").split(".");
I would do this:
var decPart = (n+"").split(".");
Specifically, I was using 100233.1 and I wanted the answer “.1”.
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('.').length; decimals = decimals.toFixed(decimalPlaces); console.log(decimals); //Returns 0.2
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