将浮点数四舍五入到小数点后两位的最佳做法是什么? [英] What's the best practice to round a float to 2 decimals?

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

问题描述

我使用的是 Eclipse + Android SDK.

I'm using eclipse + Android SDK.

我需要将浮点值四舍五入到 2 位小数.我通常使用 Math 库使用下一个技巧".

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?

推荐答案

2 年前我在 Java 中从事统计工作,但我仍然得到了一个函数的代码,该函数允许您将数字四舍五入为您想要的小数位数想.现在你需要两个,但也许你想尝试用 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();
}

您需要决定是向上还是向下取整.在我的示例代码中,我进行了四舍五入.

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

希望有帮助.

编辑

如果你想在它们为零时保留小数位数(我猜它只是为了向用户显示)你只需要将函数类型从 float 更改为 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;
}

然后这样调用函数:

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

这将打印:

2.30

这篇关于将浮点数四舍五入到小数点后两位的最佳做法是什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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