Win a copy of Re-engineering Legacy Software this week in the Refactoring forum
or Docker in Action in the Cloud/Virtualization forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Double multiplication problem

 
Prasanna Kulkarni
Greenhorn
Posts: 15
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi, this is something funny

double amount = 128.98;
System.out.println(amount*100);

This gives answer - 12897.999999999998 and not 12898.00 !

This only happens after 128.98 [E.g for 128.98, 129.98 etc] - also specifically for 0.98, not even 0.99...

Anybody knows the reason ?
 
Campbell Ritchie
Sheriff
Posts: 48415
56
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
More of a beginner's question. That sort of thing happens all the time, when you least expect it, and that's why you don't use double arithmetic for money.

We have a FAQ (no 20) with useful links.
 
Jigar Naik
Ranch Hand
Posts: 762
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Which data type should we use for arithmetic option of currency ?
 
Paul Clapham
Sheriff
Pie
Posts: 20758
30
Eclipse IDE Firefox Browser MySQL Database
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
BigDecimal, or maybe BigInteger depending on how your currency works.
 
Campbell Ritchie
Sheriff
Posts: 48415
56
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
You can get away with integer arithmetic if you declare your money in cents/pence/etc. This thread shows an example of the use of BigDecimal.
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic