Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Finding the number of places after the decimal point of a Double

Tags:

c#

I have a Double value:

double a = 4.5565;

What is the easiest way to calculate the number of digits after the decimal point (4 in this case).

I know that I can convert to string and do a split and take the length. But is there an easier way?

like image 973
blitzkriegz Avatar asked Feb 21 '12 22:02

blitzkriegz


People also ask

How do you know how many decimal places are in a double?

There are no decimal digits in a double. There are binary digits. Another way of looking at it: A double, at the hardware level on Intel platforms, is a 52-bit integer. And there is an 11-bit number that tells you where to put the decimal point.

How many decimal places of accuracy does a double have?

Double precision numbers are accurate up to sixteen decimal places but after calculations have been done there may be some rounding errors to account for.

How do you double only show two decimal places?

Just use %. 2f as the format specifier. This will make the Java printf format a double to two decimal places.


2 Answers

There's no easy way, especially since the number of digits mathematically speaking might be far more than displayed. For example, 4.5565 is actually stored as 4.556499999999999772626324556767940521240234375 (thanks to harold for calculating that). You're very unlikely to find a useful solution to this problem.

EDIT

You could come up with some algorithm that works like this: if, as you calculate the decimal representation, you find a certain number of 9s (or zeros) in succession, you round up (or down) to the last place before the series of 9s (or zeros) began. I suspect that you would find more trouble down that road than you would anticipate.

like image 134
phoog Avatar answered Oct 21 '22 23:10

phoog


var precision = 0;
var x = 1.345678901m;

while (x*(decimal)Math.Pow(10,precision) != 
         Math.Round(x*(decimal)Math.Pow(10,precision))) 
   precision++;

precision will be equal to the number of significant digits of the decimal value (setting x to 1.23456000 will result in a precision of 5 even though 8 digits were originally specified in the literal). This executes in time proportional to the number of decimal places. It counts the number of fractional digits ONLY; you can count the number of places to the left of the decimal point by taking the integer part of Math.Log10(x). It works best with decimals as they have better value precision so there is less rounding error.

like image 43
KeithS Avatar answered Oct 21 '22 23:10

KeithS