Mohammad Faisal
Mohammad Faisal

Reputation: 5959

System.out.printf() for float datatype

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

Answers (2)

Evgeniy Dorofeev
Evgeniy Dorofeev

Reputation: 136002

try

double x = 12.345;
System.out.printf("%18.7f%n", x);
...

float precision is too low

Upvotes: 1

Alepac
Alepac

Reputation: 1831

The problem regards the IEEE 754 binary floating point representation.

Please see this link for a complete description of your issue.

Upvotes: 2

Related Questions