有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

java语句优化的可能性?

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;
}

有没有可能简化这段代码而不太降低性能?看起来做得不太好


共 (2) 个答案

  1. # 1 楼答案

    对我来说没问题。我看不出有什么大的优化可以在这里完成。它也很干净。但是,您可能希望看到相同算法的alternative implementations

  2. # 2 楼答案

    Is it possible to simplify this piece of code without slowing down performance too much?

    如果我理解你的问题,是的!您可以将该方法设置为静态。您还可以使用^{}显著缩短它

    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);
    }