Skip to content
Related Articles
Open in App
Not now

Related Articles

How to get decimal portion of a number using JavaScript ?

Improve Article
Save Article
  • Last Updated : 16 Jan, 2023
Improve Article
Save Article

Given a float number, The task is to separate the number into integer and decimal parts using JavaScript. For example, a value of 15.6 would be split into two numbers, i.e. 15 and 0.6 Here are a few methods discussed. 

Javascript String split() Method: This method is used to split a string into an array of substrings and returns the new array. 

Syntax: 

string.split(separator, limit)

Parameters:

  • separator: This parameter is optional. It specifies the character, or the regular expression, to use for splitting the string. If not used, the whole string will be returned (an array with only one item) 
  • limit: This parameter is optional. It specifies the integer that specifies the number of splits, items beyond the split limit will be excluded from the array. 

Return value: Returns a new Array, having the split items.

Example: This example first converts the number to string then remove the portion before the decimal using split() method

HTML




<h1 style="color:green;">
    GeeksforGeeks
</h1>
<p id="GFG_UP">
</p>
  
<button onclick="GFG_Fun()">
    click here
</button>
<p id="GFG_DOWN"></p>
  
<script>
    var up = document.getElementById('GFG_UP');
    var n = -2.50999974435;
    up.innerHTML = n;
    var down = document.getElementById('GFG_DOWN');
      
    function GFG_Fun() {
        down.innerHTML = (n + "").split(".")[1];
    }
</script>


Output: 

How to get decimal portion of a number using JavaScript ?

How to get decimal portion of a number using JavaScript ?

JavaScript Math.abs( ) and Math.floor( ):  

  • Math.abs( ): The Math.abs() function in JavaScript is used to return the absolute value of a number. It takes a number as its parameter and returns its absolute value.
  • Math.floor( ): The Math.floor() function in JavaScript is used to round off the number passed as a parameter to its nearest integer in a Downward direction of rounding i.g towards the lesser value.

Example: This example subtracts the floor of the number by original number to get the decimal portion. But in this case, we’ll get the exact portion after decimal. We’ll get the approximate result.

HTML




<h1 style="color:green;">
    GeeksforGeeks
</h1>
<p id="GFG_UP">
</p>
  
<button onclick="GFG_Fun()">
    click here
</button>
<p id="GFG_DOWN"></p>
  
<script>
    var up = document.getElementById('GFG_UP');
    var n = 2.57;
    up.innerHTML = n;
    var down = document.getElementById('GFG_DOWN');
      
    function GFG_Fun() {
        n = Math.abs(n)
        down.innerHTML = n - Math.floor(n);
    }
</script>


Output: 

How to get decimal portion of a number using JavaScript ?

How to get decimal portion of a number using JavaScript ?


My Personal Notes arrow_drop_up
Related Articles

Start Your Coding Journey Now!