Categories
JavaScript Answers

How to Get the Decimal Places of a Floating Point Number in JavaScript?

Spread the love

Sometimes, we want to get the decimal places of a floating point number in JavaScript.

In this article, we’ll look at how to get the decimal places of a floating point number in JavaScript.

Get the Decimal Places of a Floating Point Number in JavaScript

To get the decimal places of a floating point number in JavaScript, we can convert it to a string and split it by the decimal point.

Then we can get the number of characters after the point.

For instance, we write:

const [, decimal] = (12.3456).toString().split(".")
const precision = decimal.length;
console.log(precision)

to call toString on 12.3456 to convert it to a string.

Then we call split with '.' on the string to split it by the decimal place.

Next, we assign the 2nd entry from the split string array to decimal.

And the we get the length of decimal and assign it to precision.

Therefore, precision is 4 according to the console log.

Conclusion

To get the decimal places of a floating point number in JavaScript, we can convert it to a string and split it by the decimal point.

Then we can get the number of characters after the point.

By John Au-Yeung

Web developer specializing in React, Vue, and front end development.

Leave a Reply

Your email address will not be published. Required fields are marked *