2

Possible Duplicate:
How to round a number to n decimal places in Java

When multiplying two numbers in java happens this:

double a = 9.495 * 100;

Expected result:

a = 949.5;

But the obtained result is:

a = 949.4999999999999

When I try to round number 9.495 in two decimal places the result is 9.49 instead of 9.50

Any ideas how to solve this problem?

Community
  • 1
  • 1
nikolavas
  • 63
  • 1
  • 2
  • 7
  • 3
    This is a classic misunderstanding of how floating-point numbers work. Please look up many of the existing questions on the subject. – Yuval Adam Dec 14 '11 at 14:27
  • 1
    See http://stackoverflow.com/questions/3730019/why-not-use-double-or-float-to-represent-currency. This question is asked nearly every day. – JB Nizet Dec 14 '11 at 14:28

3 Answers3

7

If you want accurate floating point computations, do not use the float or double types, but rather make use of the BigDecimal class.

Costi Ciudatu
  • 37,042
  • 7
  • 56
  • 92
  • not sure why this was voted down? – Sid Malani Dec 14 '11 at 14:31
  • me neither, I was waiting for some explaining comment... – Costi Ciudatu Dec 14 '11 at 14:32
  • I'm guessing it was because BigDecimal doesn't really solve the problems with floating point operations: there may be a finite decimal representation for 1/5, but there isn't for 1/3, 1/7, 1/11, 1/13, and so on. On one level, it only makes the errors more in tune with what we expect from our experience calculating in decimal representation, so "accurate" seems a very strong claim...though looking more closely, it also does a lot to ensure clients understand and decide how to deal with errors when they arise. – Theodore Murdock Apr 24 '14 at 00:23
2

This is a side effect of floating point calculations, and is well understood, but not necessarily intuitive. This question has actually been asked literally thousands of times, and you need to study how floating point arithmetic works.

To get around this, if you only need 2-decimal precision, then use a integer instead.

For example, if you're dealing with currency, and you want to buy a 100 items for $4.95, then you represent the cost of that value as the integer "495", an multiply that by 100, which gives you "49500". You always treat the last two digits as cents, so "49500" is $495.00.

jefflunt
  • 33,527
  • 7
  • 88
  • 126
  • and this one? Why are correct answers being voted down? – Sid Malani Dec 14 '11 at 14:33
  • Possibly because we're answering rather than voting to close as duplicate, since this is a duplicate to the max. :) It's just a vote - no biggie. This is probably one of the most asked questions in computer science. – jefflunt Dec 14 '11 at 14:35
1

You cannot. Floating point and double precision numbers in a computer cannot represent all possible values.