Take the 2-minute tour ×

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?

share|improve this question
Shouldn't 3.2 be split into 3 and 0.2? –  Surreal Dreams Dec 22 '10 at 18:28
Yes. Typo error –  Oscar Dec 23 '10 at 9:21
add comment

6 Answers

up vote 71 down vote accepted

Use 1, not 2.

js> 2.3 % 1
share|improve this answer
Thanks. It works fine. –  Oscar Dec 23 '10 at 9:20
You just saved my life :) –  Shikiryu Apr 8 '11 at 14:39
Sweet, that simplified a nasty problem for me. –  Falkayn Jun 29 '12 at 5:11
add comment
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)
share|improve this answer
If you already have the integer portion, there's no need to call Math.floor() again -- just use the integer portion that you've calculated. –  tvanfosson Dec 22 '10 at 18:29
add comment

You could convert to string, right?

n = (n + "").split(".");
share|improve this answer
add comment

You could convert it to a string and use the replace method to replace the integer part with zero, then convert the result back to a number :

var number = 123.123812,
    decimals = +number.toString().replace(/^[^\.]+/,'0');
share|improve this answer
True, you could. –  I. J. Kennedy Nov 6 '13 at 2:24
add comment

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".

share|improve this answer
add comment
float a=3.2;
int b=(int)a; // you'll get output b=3 here;
int c=(int)a-b; // you'll get c=.2 value here
share|improve this answer
that doesn't look like javascript to me! –  Ch'marr Aug 8 '13 at 1:31
-1. No javascript here, moreover, c = 0 –  pckill Feb 3 at 14:53
add comment

Your Answer


