private String formatPrice(int price) {
String p = "";
if (price > 10000000) {
p = " (" + ((double) Math.round(price / 100000) / 10) + "m)";
} else if (price > 100000) {
p = " (" + (price / 1000) + "k)";
} else if (price > 1000) {
p = " (" + ((double) Math.round(price / 100) / 10) + "k)";
} else if (price > 0) {
p = " (" + price + "gp)";
}
return p;
}
是否可以简化这段代码而不过多降低性能?看起来做得不太好。
最佳答案
Is it possible to simplify this piece of code without slowing down performance too much?
如果我理解你的问题,是的!您可以将该方法设为静态。您还可以使用 String.format()
显着缩短它
private static String formatPrice(int price) {
if (price < 0) {
return "";
}
if (price > 1000 * 1000) {
return String.format("(%.1fm)", ((double) price) / (1000 * 1000));
} else if (price > 1000) {
return String.format("(%dk)", price / 1000);
}
return String.format("(%dgp)", price);
}
关于java - 通过堆叠 if 语句进行优化的可能性?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24921450/