Win a copy of Murach's Python Programming this week in the Jython/Python forum!
  • Post Reply Bookmark Topic Watch Topic
  • New Topic

Double multiplication problem  RSS feed

 
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: 53769
127
  • 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
Posts: 22185
38
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: 53769
127
  • 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
Boost this thread!