将 double 值截断为 6 位小数

nik*_*hil 1 java math truncate

我正在解决一个需要截断输出的问题,令我惊讶的是,我无法找到一种在 java 中截断数字的方法。

输出需要是后跟 6 位小数的数字。

我想要的是 double truncate(double number,int places)输出是 truncate(14/3.0) = 4.666666.

但我得到的是

public static double round(double value, int places) {
    if (places < 0) throw new IllegalArgumentException();

    long factor = (long) Math.pow(10, places);
    value = value * factor;
    long tmp = Math.round(value);
    return (double) tmp / factor;
  }
// rounds( 14/3.0 , 6 ) = 4.666667
Run Code Online (Sandbox Code Playgroud)

随着String.format我得到

String.format("%.6f", 14/3.0) = 4.666667
Run Code Online (Sandbox Code Playgroud)

我还尝试了我在 stackoverflow 上找到的一个解决方案,该解决方案建议使用 BigDecimal 并且给了我相同的答案。

NumberFormat 似乎也以同样的方式工作

java.text.NumberFormat f = java.text.NumberFormat.getNumberInstance();
f.setMinimumFractionDigits(6);
System.out.println(f.format(14/3.0)); // 4.666667
Run Code Online (Sandbox Code Playgroud)

是否有内置方法可以执行此操作,还是我需要使用 BigInteger 之类的方法编写自己的方法?有什么我做错了吗?

ass*_*ias 5

这是因为你不是截断而是四舍五入:

long tmp = Math.round(value);
Run Code Online (Sandbox Code Playgroud)

如果您改用演员表,它应该可以工作:

long tmp = (long) value;
Run Code Online (Sandbox Code Playgroud)

所以下面的代码输出4.666666如你所愿:

public static void main(String[] args) throws Exception {
    System.out.println(truncate(14/3.0, 6));
}

public static double truncate(double value, int places) {
    if (places < 0) {
        throw new IllegalArgumentException();
    }

    long factor = (long) Math.pow(10, places);
    value = value * factor;
    long tmp = (long) value;
    return (double) tmp / factor;
}
Run Code Online (Sandbox Code Playgroud)

  • @nikhil 在您的 `round` 方法中,进行替换我建议将该方法转换为您正在寻找的 `truncate` 方法。 (2认同)