372

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:

remainder = 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 // gives remainder = 1.1 

What I am missing here?

4
  • 2
    Notice that n = Math.floor(n); is only returning your desired result (the integer portion) for non-negative numbers Commented Jun 10, 2015 at 11:06
  • Simplfy use % 1 not % 2 Commented Oct 19, 2018 at 13:54
  • 5
    decimalPart = number - Math.floor(number) further, you can add precision to it. parseFloat(decimalPart.toPrecision(3)) // floating point with precision till 3 digits Commented Jul 4, 2020 at 8:40
  • For getting integer portion of float use Math.trunc(), not Math.floor() Commented Oct 27, 2023 at 8:05

32 Answers 32

1
2
0

Reading and inspecting all the answers , I assumed it would be a good idea to share another approach to achieve "Getting Fractional Part of Number in js" :

const fractionCount = (number)=>{ let count = 0; while(number !== Math.floor(number)){ number*=10; count++; } return count; } console.log(fractionCount(2.3456790))

Sign up to request clarification or add additional context in comments.

Comments

-1

Wow, leave it to StackOverflow to overcomplicate things.

Why not just do this:

function splitDecimals(amt: number): [number, number] { const integerPart = (amt < 0 ? '-' : '') + Math.floor(Math.abs(amt)).toString(); const amountString = amt.toString(); const decimalPart = amountString.length > integerPart.length ? amountString.slice(integerPart.length) : '0'; return [Number.parseInt(integerPart), Number.parseFloat(decimalPart)]; } 

If you ignore the Number.parseX you get two nice strings, otherwise you get two nice numbers, which is the best you can do if you don't know the number of decimals.

123.4567 => [123, 0.4567] 0.111222333444555 => [0, 0.111222333444555] -123.4567 => [-123, 0.4567] 123.111222333444 => [123, 0.111222333444] 111222333444555.11 => [111222333444555, 0.11] 2230000000 => [2230000000, 0] 

Comments

1
2

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.