Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get decimal portion of a number with JavaScript

Use 1, not 2.

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(".");

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.

I would do this:

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

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


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

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