什么是圆一个浮到2位小数的最佳做法是什么? [英] What's the best practice to round a float to 2 decimals?

查看:223
本文介绍了什么是圆一个浮到2位小数的最佳做法是什么?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我使用的Eclipse + Android SDK中。

I'm using eclipse + Android SDK.

我要圆一个浮点数值2位小数。我通常使用的下一个绝招用数学库。

I need to round a float value to 2 decimals. I usually use the next "trick" using Math library.

float accelerometerX = accelerometerX * 100;
    accelerometerX = round(accelerometerX);
    Log.d("Test","" + accelerometerX/100);

但我觉得这是不是做到这一点的最好办法。

But I feel it is not the best way to do it.

有一个库做这些类型的操作?

Is there a library to do these type of operations?

在此先感谢。

推荐答案

我在Java中的统计数据2年前工作,我仍然得到了$ C $一个功能,可以让您以一个数字来数CS要小数。现在,你需要两个,但也许你想用3〜尝试比较结果,而该功能为您提供了这种自由。

I was working with statistics in Java 2 years ago and I still got the codes of a function that allows you to round a number to the number of decimals that you want. Now you need two, but maybe you would like to try with 3 to compare results, and this function gives you this freedom.

    /**
     * Round to certain number of decimals
     * 
     * @param d
     * @param decimalPlace
     * @return
     */
    public static float round(float d, int decimalPlace) {
        BigDecimal bd = new BigDecimal(Float.toString(d));
        bd = bd.setScale(decimalPlace, BigDecimal.ROUND_HALF_UP);
        return bd.floatValue();
    }

您需要决定是否要舍向上或向下。在我的例子code我围捕。

You need to decide if you want to round up or down. In my sample code I am rounding up.

希望它帮助。

修改

如果你想preserve的小数位数时,他们都为零(我猜它只是用于显示用户),你只需要从浮动改变函数类型为BigDecimal,像这样的:

If you want to preserve the number of decimals when they are zero (I guess it is just for displaying to the user) you just have to change the function type from float to BigDecimal, like this:

public static BigDecimal round(float d, int decimalPlace) {
        BigDecimal bd = new BigDecimal(Float.toString(d));
        bd = bd.setScale(decimalPlace, BigDecimal.ROUND_HALF_UP);       
        return bd;
    }

,然后调用函数是这样的:

And then call the function this way:

            float x = 2.3f;
        BigDecimal result;
        result=round(x,2);
        System.out.println(result);

这将打印:

2.30

这篇关于什么是圆一个浮到2位小数的最佳做法是什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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