Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Rounding a double to 5 decimal places in Java ME

How do I round a double to 5 decimal places, without using DecimalFormat?

like image 772
Kevin Boyd Avatar asked Sep 20 '09 14:09

Kevin Boyd


2 Answers

You can round to the fifth decimal place by making it the first decimal place by multiplying your number. Then do normal rounding, and make it the fifth decimal place again.

Let's say the value to round is a double named x:

double factor = 1e5; // = 1 * 10^5 = 100000.
double result = Math.round(x * factor) / factor;

If you want to round to 6 decimal places, let factor be 1e6, and so on.

like image 139
Joren Avatar answered Sep 26 '22 18:09

Joren


Whatever you do, if you end up with a double value it's unlikely to be exactly 5 decimal places. That just isn't the way binary floating point arithmetic works. The best you'll do is "the double value closest to the original value rounded to 5 decimal places". If you were to print out the exact value of that double, it would still probably have more than 5 decimal places.

If you really want exact decimal values, you should use BigDecimal.

like image 41
Jon Skeet Avatar answered Sep 24 '22 18:09

Jon Skeet