354

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?

Magne
  • 16,401
  • 10
  • 68
  • 88
Oscar
  • 3,551
  • 2
  • 15
  • 5

32 Answers32

479

Use 1, not 2.

js> 2.3 % 1
0.2999999999999998
Ignacio Vazquez-Abrams
  • 776,304
  • 153
  • 1,341
  • 1,358
  • 99
    In a world where 0.2999999999999998 is equal to 0.3 this may be acceptable. To me it isn't... Hence, to solve this challenge I'd refrain from using `Math.*` or `%` operations. – Marcel Stör Apr 02 '14 at 14:04
  • 84
    To avoid the floating point rounding problems noted, using `toFixed` could help in some situations e.g. `(2.3 % 1).toFixed(4)` == `"0.3000"`. – Brian M. Hunt Jun 16 '14 at 14:21
  • 22
    `(2.3 % 1).toFixed(4).substring(2)` = `"3000"` if you need it without the `0.` – Simon_Weaver Oct 02 '15 at 09:22
  • 31
    In a world where the number `2.3` has arisen, and not `2` or `3`, the number `0.2999999999999998` is perfectly acceptable despite how insulting it looks to human eyes. – Gershom Maes Apr 09 '17 at 20:08
  • It's not acceptable if you are trying to format a number for display – Greg Reynolds Oct 15 '19 at 15:58
  • 12
    @GershomMaes there are a variety of circumstances where that number is not acceptable. – Adam Leggett Oct 17 '19 at 20:28
  • 1
    I agree! My previous comment is not well-written: I was suggesting that when dealing in floats, we should expect binary-unrepresentable values to be approximated with ugly trailing decimals. But you're definitely right: often our code expects values to be rounded to a certain number of places. – Gershom Maes Oct 21 '19 at 15:49
  • the answer isn't acceptable since it's not a perfect 3, neither are the comments sine they transform the number to string. Is there a strict math solution to it? – EugenSunic Dec 07 '19 at 20:30
  • 2
    @MarcelStör I'm sorry but in maths .3 is IS equal to .29999999 (going on forever) Let's use a simpler example so you get the idea .99999... = 1 1.(x = .999999...). 2.(10x = 9.999999) 3.(10x - x = 10 - .999... = 9) 4. (9x = 9) x = 9/9 x = 1 AND x = .999.... We can take this idea and extend it to any decimal place with a forever repeating 9 (unless you have a contradiction to that rule) – Abe Jul 06 '20 at 16:57
  • 3
    when you deal with monetary amounts, 2.9999... is not acceptable, also computers and mathematics differ: computers have a limit on the decimal numbers so have to truncate somewhere, math doesn't have that limit, so when doing programming you are not in the theory mathematical area, you are in the computer with limitations area. – Pablo Pazos Jul 11 '20 at 23:20
  • 1
    If you are dealing with monetary amounts you should use fixed point. – Timmmm Oct 23 '20 at 10:15
  • @Abe, `.3` IS equal to `0.2999` repeating, but `.3` IS NOT equal to `0.2999999999999998` – Brian Hannay Jan 21 '21 at 04:11
  • `parseFloat((3.2%1).toFixed(2))` it gives you `0.2` – Chandresh Feb 27 '21 at 10:26
  • 3
    yall need to read up on floating point arithmetic. just like you cant represent 1/3 in decimal without an infinite amount of digits, you can also not represent 0.3 in binary without an infinite amount of digits. if this isnt acceptable to you for any reason other than display purposes, then nothin will be. Js already uses 64 bit fp for arithmetic, and thats the best you're getting if you intend on keeping hardware support. Unless you intend on writing a library to do math in a different base, the only thing you would get is a lot more 9s before the final 8 with say a 128 bit float/fixed point. – TrisT Sep 08 '21 at 07:04
  • 1
    Anyone convinced that this answer is wrong (Wrong for your specific use case? Maybe. Wrong in general? Nope!), you're playing with foot-guns. I see someone here talking about currency. Javascript uses floating-point arithmetic, which *isn't exact*, even if it is usually formatted pleasingly enough. This type of number is ***not*** suitable for currency, and you need to consider its inexact nature when coding. Also note: `3.2 % 1` yields `0.20000000000000018`, and *yet* `((3.2 % 1) + 3) === 3.2` evaluates to true. – snarf Dec 12 '21 at 17:55
  • To note: -3.2 % 1 = 0.8. For negative number the result does not just take the decimals, but 1 - decimals. – Gabriel Beauchemin-Dauphinais Mar 18 '23 at 17:31
133
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)
greenimpala
  • 3,777
  • 3
  • 31
  • 39
  • 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
  • 5
    `var n = 3.2, integr = Math.floor(n), decimal = n - integr;` use _Math.floor()_ just once. `integr = 3; decimal = 0.20000000000000018;` – Nurlan Mar 18 '16 at 04:29
  • 5
    In order to work with negative number, simply swap `Math.floor` with `Math.trunc`. – Igor Silva Oct 19 '18 at 12:49
  • this was returning a non exact number like I expected to get 0.80 from 100.80, not 0.79999... I solved this by adding decimal.toFixed(2) – Luis Febro Feb 04 '20 at 03:21
99

You could convert to string, right?

n = (n + "").split(".");
sdleihssirhc
  • 42,000
  • 6
  • 53
  • 67
  • 30
    This works fine everywhere except continental Europe where a comma , is the decimal separator. If you plan on using this, remember to take that into account if you are multi-national and target europe, as this solution won't do a great job for them. – cdmdotnet Jun 17 '15 at 22:56
  • 19
    I'm from continental Europe with a French Firefox and it works. Normally we would use the comma as decimal separator in France. The reason being that in JavaScript there is no culture involved when converting a Number to string, although I would prefer using `n.toString()` instead of `n + ""` because it is more readable. – Gabriel Hautclocq Jul 11 '17 at 15:07
  • 5
    If speed is critical then `n + ""` is indeed better (see https://jsperf.com/number-vs-number-tostring-vs-string-number) – Gabriel Hautclocq Jul 11 '17 at 15:22
  • 1
    @cdmdotnet JS uses `.` as a decimal separator so you are fine everywhere if your input variable's type is float. You only have to deal with that issue if your input is string. I also have to note that this answer returns a string in an array. A more complete solution is `parseFloat('0.' + (n + '').split('.')[1])` – totymedli Mar 30 '19 at 01:59
  • @cdmdotnet location independent solution is here: https://stackoverflow.com/a/59469716/1742529 – user1742529 Dec 24 '19 at 13:46
  • Sure you could convert to a string if you want to do it completely wrong. – Timmmm Oct 23 '20 at 10:13
  • Try instead with `.split(/\D/)` to split on the non-digit, so it can accept . , and asian and other scripts too I suppose. – Simon B. Sep 08 '21 at 15:01
  • All America's countries but USA, Jamaica and Guyana also use comma as the decimal separator! @cdmdotnet ! – Heitor Apr 20 '22 at 19:25
  • worked here : `$(".price").each(function () { $(this).val().split(".")[1] === '0' ? $(this).val($(this).val().split(".")[0]) : $(this).val() })` – Abdelouahab Feb 16 '23 at 10:31
41

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

Marcel Stör
  • 22,695
  • 19
  • 92
  • 198
jomofrodo
  • 1,119
  • 11
  • 19
  • 9
    I generally agree but you cannot rely on '.' the regex as [the decimal separator is an i18n character](http://en.wikipedia.org/wiki/Decimal_separator). – Marcel Stör Apr 02 '14 at 14:08
  • I realize I should point out the obvious -- my "answer" is just a very slight reworking of sdleihssirhc's answer – jomofrodo Apr 03 '14 at 17:51
  • 2
    @jomofrodo Actually, some might want the non rounded value. I don't recall the OP asking for a rounded value, just split values. – VVV Oct 26 '14 at 23:17
  • 1
    @VVV yes, some might want the non rounded value. But just because you may want precision to 9 decimal places doesn't mean your input data actually supports it. That is why it is called "false precision". If your input is 3.1, the most precision your answer can have is tenths, i.e., .1. If you answer .09 it implies that you have actually calculated/measured down to 100ths precision, when in fact the original input was only accurate to 10ths precision. – jomofrodo Nov 14 '14 at 19:11
  • 1
    @MarcelStör that can be easily handled: var decPart = (n.toLocaleString("en")).split(".")[1]; – jem Sep 03 '17 at 15:21
  • I feel as though your answer is the best so far, but still incomplete. Either way, much better than the accepted answer. The result should surely be a number, AKA a float in this case? So, maybe just wrap it in a parseFloat: var decPart = parseFloat( (n+"").split(".")[1] ); – J. Louw May 25 '18 at 06:56
  • 3
    `.toString()` does not consider i18n. Decimal separator will always be `.` [according to MDN](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Number/toString) and [the ECMA spec](https://www.ecma-international.org/ecma-262/5.1/#sec-9.8.1) – Andrewmat Apr 14 '20 at 18:43
  • If `n` is integer this will return `undefined`. You should use: `(n+"").split(".")[1] || 0` or `(n+"").split(".")[1] || '.0'` – Eugene Mala Jan 24 '21 at 00:49
38

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

var x = 3.2;
var int_part = Math.trunc(x); // returns 3
var float_part = Number((x-int_part).toFixed(2)); // return 0.2
General Grievance
  • 4,555
  • 31
  • 31
  • 45
Zantafio
  • 527
  • 4
  • 8
  • Doesn't work if the decimal portion is longer than 2 digits long. With this approach `x = 3.2` gives you the same result as `x = 3.20499` – M - Mar 02 '23 at 05:35
27

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
Ethan
  • 3,410
  • 1
  • 28
  • 49
11

Without relying on any standard JS functions:

var a = 3.2;
var fract = a * 10 % 10 /10; //0.2
var integr = a - fract; //3

Note that it is correct only for numbers with one decimal point.

General Grievance
  • 4,555
  • 31
  • 31
  • 45
Nurlan
  • 720
  • 7
  • 12
  • 3
    Language independent because it's just pure math. Practical solution. With desired fraction length: `var factor = Math.pow(10, desiredFractionLength); var fract = a * factor % factor / factor;` – muratgozel Feb 23 '20 at 17:43
9

You can use parseInt() function to get the integer part than use that to extract the decimal part

var myNumber = 3.2;
var integerPart = parseInt(myNumber);
var decimalPart = myNumber - integerPart;

Or you could use regex like:

splitFloat = function(n){
   const regex = /(\d*)[.,]{1}(\d*)/;
   var m;

   if ((m = regex.exec(n.toString())) !== null) {
       return {
          integer:parseInt(m[1]),
          decimal:parseFloat(`0.${m[2]}`)
       }
   }
}
Sheki
  • 1,597
  • 1
  • 14
  • 25
  • 1
    decimalPart is coming `0.20000000000000018` ... this is really getting hard to do because `0.2 < 0.20000000000000018` returns true.. 3.2 supposed to return 0.2 :P making so many irregularities and using `.toFixed(2)` returns string :P – Himanshu Bansal Aug 17 '19 at 10:53
  • @HimanshuBansal that's a [JavaScript problem](https://medium.com/@sarafecadu/64-bit-floating-point-a-javascript-story-fa6aad266665) (hier a [stackeoverflow question](https://stackoverflow.com/questions/588004/is-floating-point-math-broken) to that). You could use the second methode what I suggested. – Sheki Aug 19 '19 at 20:07
  • Well i have a lil' bit different problem statement... Kinda used both of ur ways :P to solve it.. ^^ – Himanshu Bansal Aug 22 '19 at 07:36
6

The following works regardless of the regional settings for decimal separator... on the condition only one character is used for a separator.

var n = 2015.15;
var integer = Math.floor(n).toString();
var strungNumber = n.toString();
if (integer.length === strungNumber.length)
  return "0";
return strungNumber.substring(integer.length + 1);

It ain't pretty, but it's accurate.

cdmdotnet
  • 1,663
  • 3
  • 17
  • 22
  • That is of course a string, so you mayneed to parseInt() first if you want it as a number. You shouldn't need to parseFloat()... unless there's something I'm missing here with base 8 not base 10 numbers... something i vaguely remember from years ago – cdmdotnet Jun 17 '15 at 23:09
6

If precision matters and you require consistent results, here are a few propositions that will return the decimal part of any number as a string, including the leading "0.". If you need it as a float, just add var f = parseFloat( result ) in the end.

If the decimal part equals zero, "0.0" will be returned. Null, NaN and undefined numbers are not tested.

1. String.split

var nstring = (n + ""),
    narray  = nstring.split("."),
    result  = "0." + ( narray.length > 1 ? narray[1] : "0" );

2. String.substring, String.indexOf

var nstring = (n + ""),
    nindex  = nstring.indexOf("."),
    result  = "0." + (nindex > -1 ? nstring.substring(nindex + 1) : "0");

3. Math.floor, Number.toFixed, String.indexOf

var nstring = (n + ""),
    nindex  = nstring.indexOf("."),
    result  = ( nindex > -1 ? (n - Math.floor(n)).toFixed(nstring.length - nindex - 1) : "0.0");

4. Math.floor, Number.toFixed, String.split

var nstring = (n + ""),
    narray  = nstring.split("."),
    result  = (narray.length > 1 ? (n - Math.floor(n)).toFixed(narray[1].length) : "0.0");

Here is a jsPerf link: https://jsperf.com/decpart-of-number/

We can see that proposition #2 is the fastest.

Community
  • 1
  • 1
Gabriel Hautclocq
  • 3,230
  • 2
  • 26
  • 31
  • don't use any of these. they will break as soon as the number rendering switches to engineering. they are also not locale-sensitive. – Spongman Jan 30 '19 at 22:10
  • Could you explain "number rendering switches to engineering"? Also, localization is not relevant because we just want the decimal portion of a number, not a localized string representing a number. – Gabriel Hautclocq Feb 26 '19 at 09:47
6

A good option is to transform the number into a string and then split it.

// Decimal number
let number = 3.2;

// Convert it into a string
let string = number.toString();

// Split the dot
let array = string.split('.');

// Get both numbers
// The '+' sign transforms the string into a number again
let firstNumber  = +array[0]; // 3
let secondNumber = +array[1]; // 2

In one line of code

let [firstNumber, secondNumber] = [+number.toString().split('.')[0], +number.toString().split('.')[1]];
Erik Martín Jordán
  • 4,332
  • 3
  • 26
  • 36
4

Depending the usage you will give afterwards, but this simple solution could also help you.

Im not saying its a good solution, but for some concrete cases works

var a = 10.2
var c = a.toString().split(".")
console.log(c[1] == 2) //True
console.log(c[1] === 2)  //False

But it will take longer than the proposed solution by @Brian M. Hunt

(2.3 % 1).toFixed(4)
David Sánchez
  • 544
  • 8
  • 21
  • 1
    This works fine everywhere except continental Europe where a comma , is the decimal separator. If you plan on using this, remember to take that into account if you are multi-national and target europe, as this solution won't do a great job for them. – cdmdotnet Jun 17 '15 at 22:57
4

Just use modulo 1.

remainder = x % 1;
General Grievance
  • 4,555
  • 31
  • 31
  • 45
masterxilo
  • 2,503
  • 1
  • 30
  • 35
  • Not work for "3.02", with ZERO in first decimal place! I posted an answer with an efficient function, could you please test it? – Cesar Devesa Oct 05 '21 at 11:23
4

You can simply use parseInt() function to help, example:

let decimal = 3.2;
let remainder = decimal - parseInt(decimal);
document.write(remainder);
Tang Chanrith
  • 1,219
  • 12
  • 8
3

I am using:

var n = -556.123444444;
var str = n.toString();
var decimalOnly = 0;

if( str.indexOf('.') != -1 ){ //check if has decimal
    var decimalOnly = parseFloat(Math.abs(n).toString().split('.')[1]);
}

Input: -556.123444444

Result: 123444444

DavidDunham
  • 1,245
  • 1
  • 22
  • 44
2

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');
gion_13
  • 41,171
  • 10
  • 96
  • 108
  • Would this solution not work in continental europe where comma is the decimal separator?? – preston Aug 11 '15 at 05:46
  • @preston You can replace the dot in the regex with any other separator character you like (such as `/^[^,]/`), but you should then leave the result as a string (remove the `+` operator) in order to avoid `NaN` results. – gion_13 Aug 11 '15 at 13:37
  • That's not how this works, one makes their code universal or it deemed to fail. – vanowm Nov 17 '20 at 12:28
  • I think you mean doomed to flail – code_monk May 26 '21 at 21:27
2

Math functions are faster, but always returns not native expected values. Easiest way that i found is

(3.2+'').replace(/^[-\d]+\./, '')
Vasilii Suricov
  • 871
  • 12
  • 18
2

The best way to avoid mathematical imprecision is to convert to a string, but ensure that it is in the "dot" format you expect by using toLocaleString:

function getDecimals(n) {
  // Note that maximumSignificantDigits defaults to 3 so your decimals will be rounded if not changed.
  const parts = n.toLocaleString('en-US', { maximumSignificantDigits: 18 }).split('.')
  return parts.length > 1 ? Number('0.' + parts[1]) : 0
}

console.log(getDecimals(10.58))
Dominic
  • 62,658
  • 20
  • 139
  • 163
2

Solution

The simplest way is to use the mod (%) operator:

var decimal = n % 1;

Explanation

The mod operator gives the remainder of the arithmetical division.

Example: 14 % 4 is 2 because 14 / 4 is 3 and its remainder is 2.

Then, since n % 1 is always between 0 and 1 or [0, 1) it corresponds to the decimal part of n.

1

I had a case where I knew all the numbers in question would have only one decimal and wanted to get the decimal portion as an integer so I ended up using this kind of approach:

var number = 3.1,
    decimalAsInt = Math.round((number - parseInt(number)) * 10); // returns 1

This works nicely also with integers, returning 0 in those cases.

1

Although I am very late to answer this, please have a look at the code.

let floatValue = 3.267848;
let decimalDigits = floatValue.toString().split('.')[1];
let decimalPlaces = decimalDigits.length;
let decimalDivider = Math.pow(10, decimalPlaces);
let fractionValue = decimalDigits/decimalDivider;
let integerValue = floatValue - fractionValue;

console.log("Float value: "+floatValue);
console.log("Integer value: "+integerValue);
console.log("Fraction value: "+fractionValue)
1

I like this answer https://stackoverflow.com/a/4512317/1818723 just need to apply float point fix

function fpFix(n) {
  return Math.round(n * 100000000) / 100000000;
}

let decimalPart = 2.3 % 1; //0.2999999999999998
let correct = fpFix(decimalPart); //0.3

Complete function handling negative and positive

function getDecimalPart(decNum) {
  return Math.round((decNum % 1) * 100000000) / 100000000;
}

console.log(getDecimalPart(2.3)); // 0.3
console.log(getDecimalPart(-2.3)); // -0.3
console.log(getDecimalPart(2.17247436)); // 0.17247436

P.S. If you are cryptocurrency trading platform developer or banking system developer or any JS developer ;) please apply fpFix everywhere. Thanks!

Pawel Cioch
  • 2,895
  • 1
  • 30
  • 29
1

2021 Update

Optimized version that tackles precision (or not).

// Global variables.
const DEFAULT_PRECISION = 16;
const MAX_CACHED_PRECISION = 20;

// Helper function to avoid numerical imprecision from Math.pow(10, x).
const _pow10 = p => parseFloat(`1e+${p}`);

// Cache precision coefficients, up to a precision of 20 decimal digits.
const PRECISION_COEFS = new Array(MAX_CACHED_PRECISION);
for (let i = 0; i !== MAX_CACHED_PRECISION; ++i) {
  PRECISION_COEFS[i] = _pow10(i);
}

// Function to get a power of 10 coefficient,
// optimized for both speed and precision.
const pow10 = p => PRECISION_COEFS[p] || _pow10(p);

// Function to trunc a positive number, optimized for speed.
// See: https://stackoverflow.com/questions/38702724/math-floor-vs-math-trunc-javascript
const trunc = v => (v < 1e8 && ~~v) || Math.trunc(v);

// Helper function to get the decimal part when the number is positive,
// optimized for speed.
// Note: caching 1 / c or 1e-precision still leads to numerical errors.
// So we have to pay the price of the division by c.  
const _getDecimals = (v = 0, precision = DEFAULT_PRECISION) => {
  const c = pow10(precision); // Get precision coef.
  const i = trunc(v); // Get integer.
  const d = v - i; // Get decimal.
  return Math.round(d * c) / c;
}

// Augmenting Number proto.
Number.prototype.getDecimals = function(precision) {
  return (isFinite(this) && (precision ? (
    (this < 0 && -_getDecimals(-this, precision))
      || _getDecimals(this, precision)
  ) : this % 1)) || 0;
}

// Independent function.
const getDecimals = (input, precision) => (isFinite(input) && (
  precision ? (
    (this < 0 && -_getDecimals(-this, precision))
      || _getDecimals(this, precision)
  ) : this % 1
)) || 0;

// Tests:
const test = (value, precision) => (
  console.log(value, '|', precision, '-->', value.getDecimals(precision))
);

test(1.001 % 1); // --> 0.0009999999999998899
test(1.001 % 1, 16); // --> 0.000999999999999
test(1.001 % 1, 15); // --> 0.001
test(1.001 % 1, 3); // --> 0.001
test(1.001 % 1, 2); // --> 0
test(-1.001 % 1, 16); // --> -0.000999999999999
test(-1.001 % 1, 15); // --> -0.001
test(-1.001 % 1, 3); // --> -0.001
test(-1.001 % 1, 2); // --> 0
0

After looking at several of these, I am now using...

var rtnValue = Number(7.23);
var tempDec = ((rtnValue / 1) - Math.floor(rtnValue)).toFixed(2);
Elim Garak
  • 1,728
  • 1
  • 16
  • 21
0

Floating-point decimal sign and number format can be dependent from country (.,), so independent solution, which preserved floating point part, is:

getFloatDecimalPortion = function(x) {
    x = Math.abs(parseFloat(x));
    let n = parseInt(x);
    return Number((x - n).toFixed(Math.abs((""+x).length - (""+n).length - 1)));
}

– it is internationalized solution, instead of location-dependent:

getFloatDecimalPortion = x => parseFloat("0." + ((x + "").split(".")[1]));

Solution desription step by step:

  1. parseFloat() for guaranteeing input cocrrection
  2. Math.abs() for avoiding problems with negative numbers
  3. n = parseInt(x) for getting decimal part
  4. x - n for substracting decimal part
  5. We have now number with zero decimal part, but JavaScript could give us additional floating part digits, which we do not want
  6. So, limit additional digits by calling toFixed() with count of digits in floating part of original float number x. Count is calculated as difference between length of original number x and number n in their string representation.
user1742529
  • 260
  • 4
  • 16
0

This function splits float number into integers and returns it in array:

function splitNumber(num)
{
  num = (""+num).match(/^(-?[0-9]+)([,.][0-9]+)?/)||[];
  return [ ~~num[1], +(0+num[2])||0 ];
}

console.log(splitNumber(3.02));    // [ 3,   0.2 ]
console.log(splitNumber(123.456)); // [ 123, 0.456 ]
console.log(splitNumber(789));     // [ 789, 0 ]
console.log(splitNumber(-2.7));    // [ -2,  0.7 ]
console.log(splitNumber("test"));  // [ 0,   0 ]

You can extend it to only return existing numbers and null if no number exists:

function splitNumber(num)
{
  num = (""+num).match(/^(-?[0-9]+)([,.][0-9]+)?/);
  return [ num ? ~~num[1] : null, num && num[2] ? +(0 + num[2]) : null ];
}

console.log(splitNumber(3.02));    // [ 3,    0.02 ]
console.log(splitNumber(123.456)); // [ 123,  0.456 ]
console.log(splitNumber(789));     // [ 789,  null ]
console.log(splitNumber(-2.7));    // [ -2,   0.7 ]
console.log(splitNumber("test"));  // [ null, null ]
vanowm
  • 9,466
  • 2
  • 21
  • 37
0

You can also truncate the number

function decimals(val) {
    const valStr = val.toString();
    const valTruncLength = String(Math.trunc(val)).length;

    const dec =
        valStr.length != valTruncLength
            ? valStr.substring(valTruncLength + 1)
            : "";

    return dec;
}

console.log("decimals: ", decimals(123.654321));
console.log("no decimals: ", decimals(123));
edalvb
  • 581
  • 6
  • 7
0

The following function will return an array which will have 2 elements. The first element will be the integer part and the second element will be the decimal part.

function splitNum(num) {
  num = num.toString().split('.')
  num[0] = Number(num[0])
  if (num[1]) num[1] = Number('0.' + num[1])
  else num[1] = 0
  return num
}
//call this function like this
let num = splitNum(3.2)
console.log(`Integer part is ${num[0]}`)
console.log(`Decimal part is ${num[1]}`)
//or you can call it like this
let [int, deci] = splitNum(3.2)
console.log('Intiger part is ' + int)
console.log('Decimal part is ' + deci)
Rifat Mahmud
  • 135
  • 1
  • 5
0

For example for add two numbers

function add(number1, number2) {
let decimal1 = String(number1).substring(String(number1).indexOf(".") + 1).length;
let decimal2 = String(number2).substring(String(number2).indexOf(".") + 1).length;

let z = Math.max(decimal1, decimal2);
return (number1 * Math.pow(10, z) + number2 * Math.pow(10, z)) / Math.pow(10, z);
}
ali t
  • 17
  • 5
0

Yet another way:

function fract(x) {
  return 1 - (Math.ceil(x) - x);
}

fract(2.3) // <-- 0.2999999999999998
aggregate1166877
  • 2,196
  • 23
  • 38
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))
-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]