使用内联条件语句格式化小数
我想知道为什么下面的代码不一致。我期望相同的输出,但是当使用内联条件语句时,它会在字符串中附加 .0。 我的代码有错误吗?
double d = 10.1;
String rounded = (false ? d : Math.round(d)) + "";
System.out.println(rounded);//10.0
rounded = Math.round(d) + "";
System.out.println(rounded);//10
I'm wondering why there is an inconsistency with the code below. I would expect the same output, but when using the inline conditional statement, it appends a .0 to the string.
Do I have some error in my code?
double d = 10.1;
String rounded = (false ? d : Math.round(d)) + "";
System.out.println(rounded);//10.0
rounded = Math.round(d) + "";
System.out.println(rounded);//10
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
Math.round
返回一个long
,因此条件运算符的两个操作数不具有相同的类型,因此需要遵循更复杂的规则来确定其类型整体操作,如 JLS 中定义§15.25:从5.6.2开始,二进制数字提升:
为了说明条件运算符的陷阱和一些乐趣,来自 Java 谜题(谜题 8):
此外,观看哈姆雷特和Elvis 示例(视频链接)。
Math.round
returns along
, therefore the two operands of the conditional operator do not have the same type, and thus a more complex rule is followed to determine the type of the overall operation, as defined in JLS §15.25:And from 5.6.2, binary numeric promotion:
And to illustrate the pitfalls with the conditional operator and for some fun, from Java puzzlers (puzzle 8):
Also, check out the Hamlet and Elvis examples (video links).
从三元运算符返回的类型可以被提升,以便两个潜在的返回类型匹配。这称为二进制数字提升,变量在转换为字符串之前从 long 提升为 double。
如果您遇到两个潜在返回类型均为 int 或 long 的情况:
会发生什么(不是反问句,因为我离 Java 编译器很远)?
The type returned from a ternary operator may be promoted so that the two potential return types match. This is called binary numeric promotion, and your variable is being promoted from long to double before conversion to a String.
If you had this where both potential return types are int or long:
What happens (not a rhetorical question since I'm no where near a Java compiler)?