Search code examples
javaandroidnumbersaccelerometerrounding

How to decrease accelerator data until two decimal numbers?


I'm trying to get accelerometer data (x y z) and to print it to the display. I already have some code for this:

public void onSensorChanged(SensorEvent event) {

    float x = event.values[0];
    float y = event.values[1];
    float z = event.values[2];

    float deltaX = ((y * 10)/10);
    float deltaY = ((y * 10)/10);
    float deltaZ = ((z * 10)/10);;

    tv.setText(Float.toString(deltaX)+ ", " +Float.toString(deltaY)+ ", " +Float.toString(deltaZ));

    Log.v("SensorActivity", event.toString());

}

But on display there are still numbers like 5.0972004 instead of 5.1 for instance. How to round the float number until "two decimal numbers"? Any suggestions would be helpful. Thanks in advance.


Solution

  • Instead of Float.toString(deltaX), use String.format("%.2f", deltaX)