
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Counting Numbers After Decimal Point in JavaScript
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
Advertisements