Java:如何使用三元运算符实现此目的
我的要求是,如果最后一个变量的值小于1,例如0.0045 然后我需要在小数点后打印4位数字,这样结果看起来像Java:如何使用三元运算符实现此目的,java,Java,我的要求是,如果最后一个变量的值小于1,例如0.0045 然后我需要在小数点后打印4位数字,这样结果看起来像0.0045 或者,如果最后一个变量值大于1,例如444.8183 然后,我只需要在小数点后打印两位数字,这样结果看起来就像444.82 我已经编写了这个程序,它工作得很好,但我喜欢使用三值运算器 public class Test { private static NumberUtil numberUtil = NumberUtil.getInstance(); pu
0.0045
或者,如果最后一个变量值大于1,例如444.8183
然后,我只需要在小数点后打印两位数字,这样结果看起来就像444.82
我已经编写了这个程序,它工作得很好,但我喜欢使用三值运算器
public class Test {
private static NumberUtil numberUtil = NumberUtil.getInstance();
public static void main(String args[]) {
float last = (float) 444.8183;
String result = "";
if (last > 1) {
result = numberUtil.formatNumber(last, 2);
} else {
result = numberUtil.formatNumber(last, 4);
}
System.out.println(result);
}
}
import java.text.DecimalFormat;
public class NumberUtil {
private static NumberUtil _instance = new NumberUtil();
public static NumberUtil getInstance() {
return _instance;
}
public String formatNumber(double d, int decPts) {
if (2 == decPts)
return new DecimalFormat("#,###,###,##0.00").format(d);
else if (0 == decPts)
return new DecimalFormat("#,###,###,##0").format(d);
else if (3 == decPts)
return new DecimalFormat("#,###,###,##0.000").format(d);
else if (4 == decPts)
return new DecimalFormat("0.0000").format(d);
return String.valueOf(d);
}
public double formatDoubleNumber(double d){
double newD = Math.round(d*100.0)/100.0;
return newD;
}
}
以下是方法:
result = (last > 1)
? numberUtil.formatNumber(last, 2)
: numberUtil.formatNumber(last, 4);
顺便说一下,它实际上被称为“条件运算符”。它恰好是一个“a”三值运算符(三值意味着它需要三个操作数)。我不喜欢三值运算符,但给你
result = (last > 1)? numberUtil.formatNumber(last, 2) : numberUtil.formatNumber(last, 4);
怎么样
sigFigs = (last > 1)? 2 : 4;
result = numberUtil.formatNumber(last, sigFigs);
这样拆分代码的好处是代码变成了“自文档化”。下周你仍然会记得你为什么要这么做。
result=numberrutil.formatNumber(last,(last>1)?2:4)代码>要使其更具可读性,请将三元代码放入调用中:
String result = numberUtil.formatNumber(last, last > 1 ? 2 : 4);
这里重要的是,你正在缩小三元效应的范围,使之与“最小化范围”保持一致
请注意,您不需要在测试中使用括号(代码越少越好!)。这是Java中唯一的三元运算符,不是吗?@Thilo OK是的,所以我想您可以随意调用它!这是它的正式名称,但每个人都知道你所说的“三元运算符”是什么意思,这就是大多数人所说的。代码在尽可能短之前应该尽可能清楚。亲爱的downvoter,这个答案有什么不有用的地方???我会在生产中使用这段代码,没有问题。请参阅Floris的答案(目前是最重要的答案)。相比之下,您的代码不清楚。。。它通常是使用条件运算符的代码。可读性比节省一行更重要。@tofu我完全同意可读性比代码密度更重要。对我来说,这已经足够清楚了,但另一个答案更清楚,因为三元结果是以变量名命名的。我真的只是用另一种方式回答了这个问题。可能的重复有这么多的拼写/语法错误,这个问题很容易用谷歌来回答。你不需要网络仆从为你编程。