It's not a secret anymore!
The moose likes Beginning Java and the fly likes format strings and unexpected output Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Java » Beginning Java
Bookmark "format strings and unexpected output" Watch "format strings and unexpected output" New topic

format strings and unexpected output

See Furst

Joined: Aug 04, 2010
Posts: 29
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:


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....

Doin' Java to be one of the cool kids.
I usually use Perl;
Wouter Oet
Saloon Keeper

Joined: Oct 25, 2008
Posts: 2700

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.

"Any fool can write code that a computer can understand. Good programmers write code that humans can understand." --- Martin Fowler
Please correct my English.
Shanky Sohar
Ranch Hand

Joined: Mar 17, 2010
Posts: 1051

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

SCJP6.0,My blog Ranchers from Delhi
I agree. Here's the link:
subject: format strings and unexpected output
jQuery in Action, 3rd edition