Decimal count of a Number 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.

Example

The code for this will be −

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

The output in the console will be −

9
0
raja
Published on 22-Oct-2020 13:03:30
Advertisements