java - 使用内联条件语句格式化小数

标签 java math formatting rounding

我想知道为什么与下面的代码不一致。我希望得到相同的输出,但是当使用内联条件语句时,它会在字符串中附加一个 .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

最佳答案

Math.round 返回一个long,因此条件运算符的两个操作数的类型不同,因此遵循更复杂的规则来确定整体操作的类型,如 JLS §15.25 中所定义:

Otherwise, binary numeric promotion (§5.6.2) is applied to the operand types, and the type of the conditional expression is the promoted type of the second and third operands. Note that binary numeric promotion performs unboxing conversion (§5.1.8) and value set conversion (§5.1.13).

从 5.6.2 开始,二进制数字提升:

If either operand is of type double, the other is converted to double.


并为了说明条件运算符的陷阱和一些乐趣,来自 Java puzzlers (谜题 8):

char x = 'X';
int i = 0;
System.out.print(true ? x : 0); // prints X
System.out.print(false ? i : x); // prints 88 => (int)X 

另外,查看 HamletElvis示例(视频链接)。

关于java - 使用内联条件语句格式化小数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7662156/

相关文章:

java - 从不同的目录编译java文件

algorithm - 开发一种将四个笛卡尔坐标转换为平方坐标的算法

c++ - C++ 中的 n 元组列表

android - 在 Android 中将符号转换为 HTML 实体代码

HighCharts 生成的表格

java - Jackcess 等效于具有 > ("strictly greater than") 条件的 SQL WHERE 子句

java - 如何随机化然后将 ArrayList<String> 拆分为两个偶数 ArrayList

java - 如何修复按重量对包裹进行排序的循环

algorithm - 寻找具有特定性质的整数 - 欧拉计划问题 221

c++ - Eclipse CDT 中的格式(换行)构造函数初始化程序列表