Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I get the decimal places of a floating point number in Javascript?

What I would like to have is the almost opposite of Number.prototype.toPrecision(), meaning that when i have number, how many decimals does it have? E.g.

(12.3456).getDecimals() // 4 
like image 711
JussiR Avatar asked Mar 04 '12 08:03

JussiR


People also ask

How do you get the decimal part of a float?

Using the modulo ( % ) operator The % operator is an arithmetic operator that calculates and returns the remainder after the division of two numbers. If a number is divided by 1, the remainder will be the fractional part. So, using the modulo operator will give the fractional part of a float.

How do you get a float number up to 2 decimal places?

format("%. 2f", 1.23456); This will format the floating point number 1.23456 up-to 2 decimal places, because we have used two after decimal point in formatting instruction %.

How do I get 2 decimal places in JavaScript?

Use the toFixed() method to format a number to 2 decimal places, e.g. num. toFixed(2) . The toFixed method takes a parameter, representing how many digits should appear after the decimal and returns the result.

How do you represent a floating-point number in JavaScript?

The representation of floating points in JavaScript follows the IEEE-754 format. It is a double precision format where 64 bits are allocated for every floating point.


2 Answers

For anyone wondering how to do this faster (without converting to string), here's a solution:

function precision(a) {   var e = 1;   while (Math.round(a * e) / e !== a) e *= 10;   return Math.log(e) / Math.LN10; } 

Edit: a more complete solution with edge cases covered:

function precision(a) {   if (!isFinite(a)) return 0;   var e = 1, p = 0;   while (Math.round(a * e) / e !== a) { e *= 10; p++; }   return p; } 
like image 55
Mourner Avatar answered Sep 18 '22 06:09

Mourner


One possible solution (depends on the application):

var precision = (12.3456 + "").split(".")[1].length; 
like image 27
Manish Avatar answered Sep 21 '22 06:09

Manish