Skip to content
geeksforgeeks
  • Courses
    • DSA to Development
    • Get IBM Certification
    • Newly Launched!
      • Master Django Framework
      • Become AWS Certified
    • For Working Professionals
      • Interview 101: DSA & System Design
      • Data Science Training Program
      • JAVA Backend Development (Live)
      • DevOps Engineering (LIVE)
      • Data Structures & Algorithms in Python
    • For Students
      • Placement Preparation Course
      • Data Science (Live)
      • Data Structure & Algorithm-Self Paced (C++/JAVA)
      • Master Competitive Programming (Live)
      • Full Stack Development with React & Node JS (Live)
    • Full Stack Development
    • Data Science Program
    • All Courses
  • Tutorials
    • Data Structures & Algorithms
    • ML & Data Science
    • Interview Corner
    • Programming Languages
    • Web Development
    • CS Subjects
    • DevOps And Linux
    • School Learning
  • Practice
    • Build your AI Agent
    • GfG 160
    • Problem of the Day
    • Practice Coding Problems
    • GfG SDE Sheet
  • Contests
    • Accenture Hackathon (Ending Soon!)
    • GfG Weekly [Rated Contest]
    • Job-A-Thon Hiring Challenge
    • All Contests and Events
  • JS Tutorial
  • JS Exercise
  • JS Interview Questions
  • JS Array
  • JS String
  • JS Object
  • JS Operator
  • JS Date
  • JS Error
  • JS Projects
  • JS Set
  • JS Map
  • JS RegExp
  • JS Math
  • JS Number
  • JS Boolean
  • JS Examples
  • JS Free JS Course
  • JS A to Z Guide
  • JS Formatter
Open In App
Next Article:
Generate Random Number in Given Range Using JavaScript
Next article icon

How to get decimal portion of a number using JavaScript ?

Last Updated : 30 May, 2024
Comments
Improve
Suggest changes
Like Article
Like
Report

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. 

These are the following methods:

Table of Content

  • Javascript String split() Method
  • JavaScript Math.abs( ) and Math.floor( )
  • Javascript indexOf() method
  • Using toFixed() Method

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 removes the portion before the decimal using the split() method. 

JavaScript
let n = -2.50999974435; console.log(n);  function GFG_Fun() {     console.log((n + "").split(".")[1]); } GFG_Fun() 

Output
-2.50999974435 50999974435 

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.

JavaScript
let n = 2.57; console.log(n);  function GFG_Fun() {     n = Math.abs(n)     console.log(n - Math.floor(n)); } GFG_Fun() 

Output
2.57 0.5699999999999998 

Javascript indexOf() method

Using the indexOf() method to get the decimal part of the given number, in which we convert our number into a string and then get the index of the decimal point with the help of the indexOf() method. and then extract the part of the decimal string as a substring.

Syntax:

number.toString().indexOf(".")

Example:  In this example first we convert to the string and then get the index of the decimal point and store it in a new variable, and again convert the number into a string and get the decimal part using the substring() method.

JavaScript
let number = 20.125; let decimalValue = number.toString().indexOf("."); let result = number.toString().substring(decimalValue+1); //orignal number console.log(number) //Decimal part of Number console.log(result); 

Output
20.125 125 

Using toFixed() Method

The toFixed() method formats a number using fixed-point notation and returns a string representation of the number. This method can be useful for obtaining the exact decimal part of a number by specifying the number of digits after the decimal point.

Syntax:

number.toFixed(digits);

Parameters:

  • ‘digits’: The number of digits to appear after the decimal point. This parameter is optional and defaults to 0.

Example: In this example, we use the toFixed() method to format the number to a fixed decimal point, convert it to a string, and then extract the integer and decimal parts separately.

JavaScript
let number = 15.6;  function splitNumber(number) {     let fixedNumber = number.toFixed(10);      let parts = fixedNumber.split('.');      let integerPart = parseInt(parts[0]);      let decimalPart = parseFloat('0.' + parts[1]);     return { integerPart, decimalPart }; }  let result = splitNumber(number);  console.log(result.integerPart);  console.log(result.decimalPart);  

Output
15 0.6 




Next Article
Generate Random Number in Given Range Using JavaScript

P

PranchalKatiyar
Improve
Article Tags :
  • JavaScript
  • Web Technologies
  • JavaScript-Questions

Similar Reads

  • How numbers are stored in JavaScript ?
    In this article, we will try to understand how numbers are stored in JavaScript. Like any other programming language, all the data is stored inside the computer in the form of binary numbers 0 and 1. Since computers can only understand and process data in the form of 0's and 1's. In JavaScript, ther
    6 min read
  • How to create a Number object using JavaScript ?
    In this article, we will discuss how to create a Number object using JavaScript. A number object is used to represent integers, decimal or float point numbers, and many more. The primitive wrapper object Number is used to represent and handle numbers. examples: 20, 0.25. We generally don't need to w
    2 min read
  • How to convert a value to a safe integer using JavaScript ?
    In this article, we will learn How to convert a value to a safe integer using JavaScript. We have given a number, and we have to convert it into a safe integer using JavaScript. Safe Integers are integers between -(253 - 1) and (253 - 1). Approach: First, we take input using the prompt in JavaScript
    2 min read
  • How to add float numbers using JavaScript ?
    Given two or more numbers the task is to get the float addition in the desired format with the help of JavaScript. There are two methods to solve this problem which are discussed below: Table of Content Using parseFloat() and toFixed() method Using parseFloat() and Math.round() method Using Number()
    2 min read
  • Calculate current week number in JavaScript
    Calculating the current week number involves determining which week of the year the current date falls into. The method of calculation can vary slightly depending on the rules you follow, such as which day starts the week (Sunday or Monday) and how the first week of the year is defined. For example:
    2 min read
  • How to Convert a Float Number to the Whole Number in JavaScript?
    Given a float number and the task is to convert a float number to a whole number using JavaScript. Below are various methods to convert float numbers to whole numbers in JavaScript: Table of Content Math.floor (floating argument)Math.ceil (floating argument) Math.round (floating argument)Math.trunc
    4 min read
  • How to convert Number to Boolean in JavaScript ?
    We convert a Number to Boolean by using the JavaScript Boolean() method and double NOT operator(!!). A JavaScript boolean results in one of two values i.e. true or false. However, if one wants to convert a variable that stores integer “0” or “1” into Boolean Value i.e. "false" or "true".  Below are
    2 min read
  • Convert a Number to a String in JavaScript
    These are the following ways to Convert a number to a string in JavaScript: 1. Using toString() Method (Efficient and Simple Method)This method belongs to the Number.Prototype object. It takes an integer or a floating-point number and converts it into a string type. [GFGTABS] JavaScript let a = 20;
    1 min read
  • Convert a negative number to positive in JavaScript
    In this article, we will see how we can convert a negative number to a positive number in JavaScript by the methods described below. Below are the methods to convert a negative number to a positive in JavaScript: Table of Content Multiplying by -1Using Math.abs()adding a minus signFlipping the bitUs
    4 min read
  • Check a Number is Prime or Not Using JavaScript
    A prime number is a whole number greater than 1, which has no positive divisors other than 1 and itself. In other words, prime numbers cannot be formed by multiplying two smaller natural numbers. For example: 2, 3, 5, 7, 11, and 13 are prime numbers.4, 6, 8, 9, and 12 are not prime numbers because t
    5 min read
geeksforgeeks-footer-logo
Corporate & Communications Address:
A-143, 7th Floor, Sovereign Corporate Tower, Sector- 136, Noida, Uttar Pradesh (201305)
Registered Address:
K 061, Tower K, Gulshan Vivante Apartment, Sector 137, Noida, Gautam Buddh Nagar, Uttar Pradesh, 201305
GFG App on Play Store GFG App on App Store
Advertise with us
  • Company
  • About Us
  • Legal
  • Privacy Policy
  • In Media
  • Contact Us
  • Advertise with us
  • GFG Corporate Solution
  • Placement Training Program
  • Languages
  • Python
  • Java
  • C++
  • PHP
  • GoLang
  • SQL
  • R Language
  • Android Tutorial
  • Tutorials Archive
  • DSA
  • Data Structures
  • Algorithms
  • DSA for Beginners
  • Basic DSA Problems
  • DSA Roadmap
  • Top 100 DSA Interview Problems
  • DSA Roadmap by Sandeep Jain
  • All Cheat Sheets
  • Data Science & ML
  • Data Science With Python
  • Data Science For Beginner
  • Machine Learning
  • ML Maths
  • Data Visualisation
  • Pandas
  • NumPy
  • NLP
  • Deep Learning
  • Web Technologies
  • HTML
  • CSS
  • JavaScript
  • TypeScript
  • ReactJS
  • NextJS
  • Bootstrap
  • Web Design
  • Python Tutorial
  • Python Programming Examples
  • Python Projects
  • Python Tkinter
  • Python Web Scraping
  • OpenCV Tutorial
  • Python Interview Question
  • Django
  • Computer Science
  • Operating Systems
  • Computer Network
  • Database Management System
  • Software Engineering
  • Digital Logic Design
  • Engineering Maths
  • Software Development
  • Software Testing
  • DevOps
  • Git
  • Linux
  • AWS
  • Docker
  • Kubernetes
  • Azure
  • GCP
  • DevOps Roadmap
  • System Design
  • High Level Design
  • Low Level Design
  • UML Diagrams
  • Interview Guide
  • Design Patterns
  • OOAD
  • System Design Bootcamp
  • Interview Questions
  • Inteview Preparation
  • Competitive Programming
  • Top DS or Algo for CP
  • Company-Wise Recruitment Process
  • Company-Wise Preparation
  • Aptitude Preparation
  • Puzzles
  • School Subjects
  • Mathematics
  • Physics
  • Chemistry
  • Biology
  • Social Science
  • English Grammar
  • Commerce
  • World GK
  • GeeksforGeeks Videos
  • DSA
  • Python
  • Java
  • C++
  • Web Development
  • Data Science
  • CS Subjects
@GeeksforGeeks, Sanchhaya Education Private Limited, All rights reserved
We use cookies to ensure you have the best browsing experience on our website. By using our site, you acknowledge that you have read and understood our Cookie Policy & Privacy Policy
Lightbox
Improvement
Suggest Changes
Help us improve. Share your suggestions to enhance the article. Contribute your expertise and make a difference in the GeeksforGeeks portal.
geeksforgeeks-suggest-icon
Create Improvement
Enhance the article with your expertise. Contribute to the GeeksforGeeks community and help create better learning resources for all.
geeksforgeeks-improvement-icon
Suggest Changes
min 4 words, max Words Limit:1000

Thank You!

Your suggestions are valuable to us.

What kind of Experience do you want to share?

Interview Experiences
Admission Experiences
Career Journeys
Work Experiences
Campus Experiences
Competitive Exam Experiences