Java – what is the best practice for rounding floating point numbers to 2 decimal places?

See English answers > how to round a number to N decimal places in Java 29

I need to round the floating point value to 2 decimal places I usually use the math library to use the next "skill"

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

But I don't think it's the best way

Is there a library that can perform these types of operations?

Thank you in advance

Solution

I used statistics in java two years ago, and I still got a function code that allows you to round numbers to the number of decimal places you want Now you need two, but maybe you want to compare the results with 3. 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 whether to round up or down In my sample code, I'm looking around

I hope I can help you

edit

If you want to keep the decimal places when they are zero (I guess it's just for display to users), you just need to change the function type from float to BigDecimal, as shown below:

public static BigDecimal round(float d,BigDecimal.ROUND_HALF_UP);       
    return bd;
}

Then call the function in this way:

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

This will print:

2.30
The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
分享
二维码
< <上一篇
下一篇>>