Win a copy of Programmer's Guide to Java SE 8 Oracle Certified Associate (OCA) this week in the OCAJP forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

format strings and unexpected output

 
See Furst
Greenhorn
Posts: 29
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I run the following code on Ubuntu Linux with the following JVM:

java version "1.6.0_18"
OpenJDK Runtime Environment (IcedTea6 1.8.1) (6b18-1.8.1-0ubuntu1~9.10.1)
OpenJDK Client VM (build 16.0-b13, mixed mode, sharing)


here's the code:


Here's the output:

3,678.9856

What happened to my '7'? I said 7. Did I not say .9857 not 6.... who said 6? the JVM said 6. Why?


Ah maybe I should use printf... duh...

Nope that didn't work either....
 
Wouter Oet
Saloon Keeper
Posts: 2700
IntelliJ IDE Opera
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
That's because you're using a float. A float has an imprecision just like a double (wiki). Basically that's how computers work. If you want to avoid that imprecision then you should use a BigDecimal.
 
Shanky Sohar
Ranch Hand
Posts: 1051
Eclipse IDE Firefox Browser
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
if you remove suffix "f" and tried it then it will work fine.suffix f means you are forcfully converting double value to a float and you are responsible for precision lost
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic