I’m using eclipse + Android SDK.
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?
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.
You need to decide if you want to round up or down. In my sample code I am rounding up.
Hope it helps.
EDIT
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:
And then call the function this way:
This will print: