如何在不舍入的情况下截断Java中的小数? [英] How to cut off decimal in Java WITHOUT rounding?

查看:53
本文介绍了如何在不舍入的情况下截断Java中的小数?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I have a series of Java decimals like:

0.43678436287643872
0.4323424556455654
0.6575643254344554

我希望将所有小数点后5位保留下来.这怎么可能?

I wish to cut off everything after 5 decimal places. How is this possible?

推荐答案

如果您想让事情变得简单快捷.;)

If you want to keep things fast and simple. ;)

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

打印

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

这篇关于如何在不舍入的情况下截断Java中的小数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆