Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I count the number of zero decimals in JavaScript?

How do I get the number of zero decimals behind the comma (but not the total)? So to illustrate an example:

0.00001 > 4
0.000015 > 4
0.0000105 > 4
0.001 > 2

I am looking for methods that are efficient (meaning that they optimize the calculation time).

like image 1000
JohnAndrews Avatar asked Jun 23 '15 11:06

JohnAndrews


People also ask

How do you count decimal places?

The first digit after the decimal represents the tenths place. The next digit after the decimal represents the hundredths place. The remaining digits continue to fill in the place values until there are no digits left.

What is the use of toFixed 2 in JavaScript?

The toFixed() method returns a string representation of numObj that does not use exponential notation and has exactly digits digits after the decimal place. The number is rounded if necessary, and the fractional part is padded with zeros if necessary so that it has the specified length.

How do I limit the number of decimal places in JavaScript?

JavaScript Number toFixed() The toFixed() method rounds the string to a specified number of decimals.


2 Answers

You can use logarithms to find the magnitude of the number:

var x = 0.00195;
var m = -Math.floor( Math.log(x) / Math.log(10) + 1);
document.write(m); // outputs 2

Later versions of JavaScript have Math.log10, so it would be:

var x = 0.00195;
var m = -Math.floor( Math.log10(x) + 1);
document.write(m); // outputs 2

How using the base-10 logarithm of the numbers works:

x Math.log10(x) Math.floor(Math.log10(x) + 1 )
0.1 -1 0
0.01 -2 -1
0.015 -1.8239… -1
0.001 -3 -2
0.00001 -5 -4
0.000015 -4.8239… -4
0.0000105 -4.9788… -4
like image 106
Andrew Morton Avatar answered Sep 17 '22 20:09

Andrew Morton


Use a regex to match the number of zeros after a decimal point and then count them.

var zeros = float.toString().match(/(\.0*)/)[0].length - 1;

DEMO

like image 30
Andy Avatar answered Sep 17 '22 20:09

Andy