开发者

Why do floats having trailing .0 when it is exactly an integer?

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 l开发者_如何学Coss 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?


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.


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


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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜