Why does the String.format(); gives dissimilar output

Viewed 46
public class javaloops {
    public static void main(String[] args) {
        areEqualByThreeDecimalPlaces(3.175, 3.1756);
    }

    public static void areEqualByThreeDecimalPlaces(double a, double b) {
        System.out.println(String.format("%.3f", a));
        System.out.println(String.format("%.3f", b));
    }    
}
1 Answers

The code you used will print

3.175
3.176

I suppose you expect %.3f to truncate the result.

According to the documentation for string formatters:

If the precision is less than the number of digits which would appear after the decimal point in the string returned by Float.toString(float) or Double.toString(double) respectively, then the value will be rounded using the round half up algorithm.

Related