Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Difference between valueOf() and String.format()

Tags:

java

double

Why are the values of String.valueOf(5.6d + 5.8d) and String.format("%f", 5.6d + 5.8d) diffrent?

String.valueOf(5.6d + 5.8d) will print "11.399999999999999".
String.format("%f", 5.6d + 5.8d) will print "11.400000".

Why is it so?

Edit: The question differs to Is floating point math broken? , because String.format() round up (see answers)

like image 372
akop Avatar asked Feb 17 '26 05:02

akop


1 Answers

From the documentation of Format Strings for String#format:

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.

By default, String.format("%f", ...) uses 6 decimal digits of precision; because this is fewer digits than what would appear when used by Double.toString(double) (which is equivalent to String.valueOf(double)), then the value is rounded as specified above.

like image 170
Jacob G. Avatar answered Feb 18 '26 18:02

Jacob G.



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!