Reputation: 5959
I've a very short code snippet here:
public class FormatFloat {
public static void main(String[] args) {
float x = 12.345f;
System.out.printf("%18.7f%s", x, "\n");
System.out.printf("%18.8f%s", x, "\n");
System.out.printf("%18.10f%s", x, "\n");
System.out.printf("%18.15f%s", x, "\n");
}
}
I'd supposed the output to be
12.3450000
12.34500000
12.3450000000
12.345000000000000
But I'm getting
12.3450003
12.34500027
12.3450002670
12.345000267028809
Can anybody tell me the reason behind it?
Upvotes: 1
Views: 1789
Reputation: 136002
try
double x = 12.345;
System.out.printf("%18.7f%n", x);
...
float precision is too low
Upvotes: 1