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.
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
How to get decimal portion of a number using JavaScript ?
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
Contact Us