If you are having trouble and have no knowledge about “Get the Decimal Part of a Number in JavaScript”, take a look at our instructions below to get the answer.
Brainstorming Ideas
- Convert float number to string then split the decimal part
- Minus the integer part
- Take the decimal part directly by using the division remainder
Get the Decimal Part of a Number in JS
Method 1: Convert float number to string then split the decimal part
- Step 1: Use
toString()
method to convert a number to string - Step 2: Use
split()
method to separate two parts of the string from the dot “.”. The result returns an array - Step 3: Take the second element of the array as the decimal part
Code:
// Declare a float number let x = 3.1415 // Convert x to string let str = x.toString() // Split the string, result is an array // arr[0] = 3, arr[1] = 1415 let arr = str.split(".") console.log("Decimal part of x is:", arr[1])
Result:
Decimal part of x is: 1415
Method 2: Minus the integer part to get the decimal part
Step 1: Take the integer part from the float number by using Math.trunc()
or Math.floor()
Step 2: Subtract the integer part by the float number to get the decimal part
Code:
let x = 3.1415 let y = 22.16 let intPart1 = Math.trunc(x) // Return integer part of x let intPart2 = Math.floor(y) // Round down to the nearest integer of y console.log("Decimal part of x is:", x - intPart1) console.log("Decimal part of y is:", y - intPart2)
Result:
Decimal part of x is: 0.14150000000000018
Decimal part of y is: 0.16000000000000014
Method 3: Calculate decimal as the division remainder division
Compute the remainder by %
operator
Code:
let x = 3.1415 console.log("Decimal part of x is:", x % 1)
Result:
Decimal part of x is: 0.14150000000000018
Summary
You have been through our tutorial to get the decimal part of a number in JavaScript. I hope you understand the ideas to put into practice effectively.
Maybe you are interested:
- How to add Leading Zeros to a Number in JavaScript
- How To Get The Sum Of An Array Of Numbers In JavaScript
- Extract A Number From A String In JavaScript
My name is Robert Collier. I graduated in IT at HUST university. My interest is learning programming languages; my strengths are Python, C, C++, and Machine Learning/Deep Learning/NLP. I will share all the knowledge I have through my articles. Hope you like them.
Name of the university: HUST
Major: IT
Programming Languages: Python, C, C++, Machine Learning/Deep Learning/NLP