[javascript] Get decimal portion of a number with JavaScript

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?

This question is related to javascript floating-point numbers decimal rounding

The answer is


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


A simple way of doing it is:

_x000D_
_x000D_
var x = 3.2;_x000D_
var decimals = x - Math.floor(x);_x000D_
console.log(decimals); //Returns 0.20000000000000018
_x000D_
_x000D_
_x000D_

Unfortunately, that doesn't return the exact value. However, that is easily fixed:

_x000D_
_x000D_
var x = 3.2;_x000D_
var decimals = x - Math.floor(x);_x000D_
console.log(decimals.toFixed(1)); //Returns 0.2
_x000D_
_x000D_
_x000D_

You can use this if you don't know the number of decimal places:

_x000D_
_x000D_
var x = 3.2;_x000D_
var decimals = x - Math.floor(x);_x000D_
_x000D_
var decimalPlaces = x.toString().split('.')[1].length;_x000D_
decimals = decimals.toFixed(decimalPlaces);_x000D_
_x000D_
console.log(decimals); //Returns 0.2
_x000D_
_x000D_
_x000D_


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

(3.2+'').replace(/^[-\d]+\./, '')

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]}`)
       }
   }
}

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.

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.


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


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

var rtnValue = Number(7.23);
var tempDec = ((rtnValue / 1) - Math.floor(rtnValue)).toFixed(2);

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]];

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:

_x000D_
_x000D_
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))
_x000D_
_x000D_
_x000D_


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

You could convert to string, right?

n = (n + "").split(".");

Language independent way:

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

note that it correct only for numbers with one fractioanal lenght )


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');

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)

n = Math.floor(x);
remainder = x % 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)

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!


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.


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.


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

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)

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

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

console.log(splitNumber(3.2));     // [ 3, 2 ]
console.log(splitNumber(123.456)); // [ 123, 456 ]
console.log(splitNumber(789));     // [ 789, 0 ]
console.log(splitNumber("test"));  // [ 0, 0 ]
_x000D_
_x000D_
_x000D_

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

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

console.log(splitNumber(3.2));     // [ 3, 2 ]
console.log(splitNumber(123.456)); // [ 123, 456 ]
console.log(splitNumber(789));     // [ 789, null ]
console.log(splitNumber("test"));  // [ null, null ]
_x000D_
_x000D_
_x000D_


Examples related to javascript

need to add a class to an element How to make a variable accessible outside a function? Hide Signs that Meteor.js was Used How to create a showdown.js markdown extension Please help me convert this script to a simple image slider Highlight Anchor Links when user manually scrolls? Summing radio input values How to execute an action before close metro app WinJS javascript, for loop defines a dynamic variable name Getting all files in directory with ajax

Examples related to floating-point

Convert list or numpy array of single element to float in python Convert float to string with precision & number of decimal digits specified? Float and double datatype in Java C convert floating point to int Convert String to Float in Swift How do I change data-type of pandas data frame to string with a defined format? How to check if a float value is a whole number Convert floats to ints in Pandas? Converting Float to Dollars and Cents Format / Suppress Scientific Notation from Python Pandas Aggregation Results

Examples related to numbers

how to display a javascript var in html body How to label scatterplot points by name? Allow 2 decimal places in <input type="number"> Why does the html input with type "number" allow the letter 'e' to be entered in the field? Explanation on Integer.MAX_VALUE and Integer.MIN_VALUE to find min and max value in an array Input type "number" won't resize C++ - how to find the length of an integer How to Generate a random number of fixed length using JavaScript? How do you check in python whether a string contains only numbers? Turn a single number into single digits Python

Examples related to decimal

Java and unlimited decimal places? What are the parameters for the number Pipe - Angular 2 Limit to 2 decimal places with a simple pipe C++ - Decimal to binary converting Using Math.round to round to one decimal place? String to decimal conversion: dot separation instead of comma Python: Remove division decimal Converting Decimal to Binary Java Check if decimal value is null Remove useless zero digits from decimals in PHP

Examples related to rounding

How to round a numpy array? How to pad a string with leading zeros in Python 3 Python - round up to the nearest ten How to round a Double to the nearest Int in swift? Using Math.round to round to one decimal place? How to round to 2 decimals with Python? Rounding to 2 decimal places in SQL Rounding to two decimal places in Python 2.7? Round a floating-point number down to the nearest integer? Rounding BigDecimal to *always* have two decimal places