如何在没有舍入的情况下切断Java中的小数?

Zub*_*air 8 java

我有一系列的Java小数,如:

0.43678436287643872
0.4323424556455654
0.6575643254344554
Run Code Online (Sandbox Code Playgroud)

我希望在小数点后5位切掉一切.这怎么可能?

Pet*_*rey 29

如果你想保持快速和简单的事情.;)

public static void main(String... args) {
    double[] values = {0.43678436287643872, 0.4323424556455654, 0.6575643254344554,
            -0.43678436287643872, -0.4323424556455654, -0.6575643254344554,
            -0.6575699999999999 };

    for (double v : values) 
        System.out.println(v + " => "+roundDown5(v));
}

public static double roundDown5(double d) {
    return ((long)(d * 1e5)) / 1e5;
    //Long typecast will remove the decimals
}

// Or this. Slightly slower, but faster than creating objects. ;)
public static double roundDown5(double d) {
    return Math.floor(d * 1e5) / 1e5;
}
Run Code Online (Sandbox Code Playgroud)

版画

0.43678436287643874 => 0.43678
0.4323424556455654 => 0.43234
0.6575643254344554 => 0.65756
-0.43678436287643874 => -0.43678
-0.4323424556455654 => -0.43234
-0.6575643254344554 => -0.65756
-0.6575699999999999 => -0.65756
Run Code Online (Sandbox Code Playgroud)

  • 好方案!简单而棘手.我喜欢它!谢谢 (2认同)
  • 这太棒了,谢谢!现在有很多代码重构:) (2认同)

Art*_*tem 18

float f = 0.43678436287643872;
BigDecimal fd = new BigDecimal(f);
BigDecimal cutted = fd.setScale(5, RoundingMode.DOWN);
f = cutted.floatValue();
Run Code Online (Sandbox Code Playgroud)

  • @Artem现在没有什么可以阻止你编辑你的答案 (2认同)

Kri*_*ris 9

Double.parseDouble(String.valueOf(x).substring(0,7));
Run Code Online (Sandbox Code Playgroud)

要么

Double.valueOf(String.valueOf(x).substring(0,7));
Run Code Online (Sandbox Code Playgroud)

其中x包含要剪切的值,例如0.43678436287643872


Cos*_*lis 8

DecimalFormat的也可以提供帮助这里:

    double d = 0.436789436287643872;
    DecimalFormat df = new DecimalFormat("0.#####");
    df.setRoundingMode(RoundingMode.DOWN);

    double outputNum = Double.valueOf(df.format(d));
    String outpoutString = df.format(d);
Run Code Online (Sandbox Code Playgroud)