Was it helpful?

Question

Counting numbers after decimal point in JavaScript

JavascriptWeb DevelopmentFront End TechnologyObject Oriented Programming

We are required to write a JavaScript function that takes in a number which may be an integer or a floating-point number. If it's a floating-point number, we have to return the count of numbers after the decimal point. Otherwise we should return 0.

For our example, we are considering two numbers −

const num1 = 1.123456789;
const num2 = 123456789;

Example

Following is the code −

const num1 = 1.123456789;
const num2 = 123456789;
const decimalCount = num => {
   // Convert to String
   const numStr = String(num);
   // String Contains Decimal
   if (numStr.includes('.')) {
      return numStr.split('.')[1].length;
   };
   // String Does Not Contain Decimal
   return 0;
}
console.log(decimalCount(num1)) // 9
console.log(decimalCount(num2)) // 0

Output

This will produce the following output in console −

9
0
raja
Published on 30-Sep-2020 18:03:12
Advertisements
Was it helpful?
Not affiliated with Tutorialspoint
scroll top