views:

127

answers:

3

Read this question carefully because I am not asking how to get rid of trailing zeros, that's easy.

What I am asking is why does 123d become "123.0"?

A IEEE 64-bit float can represent integers from 0 to 2^52 exactly, so this isn't a loss in precision but a decision during the implementation of Double.toString().

My question is why did they make this decision as they did? Why did they not just print 123?

+5  A: 

That way, it'd be easier to see that it was, in fact, a double, and not an int, I guess :).

jqno
+8  A: 

Among other things, it leads to clarity of representation - users are often confused when what seems to be an integer value suddenly has a long trail of digits after the decimal place after a simple arithmetic operation.

Mike Burton
Print an int, looks like an int. Print a double, looks like a double. The world makes sense.
Nick Veys
I get scared when that happens. And Numerical Methods taught me the exact reason why, in this case.
Mike Burton
A: 

toString is a very special method. It does not mean "User display string" by any stretch of the imagination (although it often happens to coincide, as with "String's" toString method)

It's actually for developers to be able to instantly grok what an object is (primarily as a debug output).

For anything to be printed out by a user, it should rendered through a formatter anyway to ensure correct max size, number of decimal points, and decimal indicator (. or ,).

In Java code, 0.0 is automatically cast to a double, so it makes perfect sense that a double would print as 0.0--it means "this is a double". I'm a little surprised it doesn't end with an "f" or "d", but that would actually be really annoying because the toString for int's is really really useful and to constantly follow it with an "i" would have pissed everyone off.

Bill K
Yes, op should go with a formatted approach.
Nicholas Jordan