Win a copy of Kotlin in Action this week in the Kotlin forum!
  • Post Reply Bookmark Topic Watch Topic
  • New Topic

Weird multiplication outcome double  RSS feed

 
Di Fusio
Greenhorn
Posts: 7
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hello JavaRanchers...

...and thank you for helping this novice Java cow.

As an assignment in a book I was tasked to write a program that alters an investment. My code is this:


Then why is my outcome not a round numer, but it has this weird trailing 4 in the last result:

Initial investment: 14000.0
Investment 40% interest: 19600.0
Investment lost 1500 dollar: 18100.0
Investment 12% interest: 20272.000000000004

I've tried searching google for it, but can't find the right search terms.

Thank you!

 
Jesper de Jong
Java Cowboy
Sheriff
Posts: 16027
87
Android IntelliJ IDE Java Scala Spring
  • Likes 1
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Welcome to the Ranch!

The double data type in Java is not infinitely precise: if you start doing calculations with it, you can get roundoff errors. Note that double in Java is represented as a 64-bit double-precision IEEE-754 number. It can't hold all decimal values with the exact value. See also question #20 in our FAQ.

If you require numbers with arbitrary precision, then have a look at the BigDecimal class.
 
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!