Wednesday, April 25, 2012

Rounding a double in Java/Android

Rounding a double can be done in many ways, and I will list some of them by inserting them into an Android helloworld example.
Run the example and you will see the differences.

HelloWorldActivity.java
public class HelloWorldActivity extends Activity {
    private final static String TAG = "HELLO_DOUBLE";
    private final static int STARTLOOPS = 0;
    private final static int ENDLOOPS = 20;
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);

        StringBuilder sb = new StringBuilder();
        double my_number = 3.72323252463374574432642356;
        double value = 0.0;

        sb.append("Pow10 Round\n");
        for(int i = STARTLOOPS ; i < ENDLOOPS ; i++) {
            value = pow10Round(my_number, i);
            sb.append("*"+i+"="+value+"\n");
        }
     
        sb.append("BigDecimal\n");
        for(int i = STARTLOOPS ; i < ENDLOOPS ; i++) {
            value = bdRound(my_number, i, BigDecimal.ROUND_HALF_UP);
            sb.append("*"+i+"="+value+"\n");
        }

        sb.append("NumberFormat\n");
        for(int i = STARTLOOPS ; i < ENDLOOPS ; i++) {
            sb.append("*"+i+"="+formatDouble(my_number,0,i)+"\n");
        }

        TextView tv = (TextView) findViewById(R.id.text);
        tv.setText(sb.toString());
    }

    public static double pow10Round(double unrounded,int precision) {
        double pow = Math.pow(10, precision);
        return Math.round(unrounded * pow) / pow;
    }

    public static double bdRound(double unrounded, int precision, int roundingMode){
        BigDecimal bd = new BigDecimal(unrounded);
        BigDecimal rounded = bd.setScale(precision, roundingMode);
        return rounded.doubleValue();
    }

    public static final NumberFormat NUMBER_FORMAT = NumberFormat.getInstance();
    public static String formatDouble(double doubleToFormat, int min, int max) {
        NUMBER_FORMAT.setMaximumFractionDigits(max);
        NUMBER_FORMAT.setMinimumFractionDigits(min);
        return NUMBER_FORMAT.format(doubleToFormat);
    }

}

main.xml
<?xml version="1.0" encoding="utf-8"?>
<ScrollView xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent" >
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="horizontal"
android:layout_width="fill_parent"
android:layout_height="fill_parent" >
<TextView
android:id="@+id/text"
android:layout_width="wrap_content"
android:layout_height="fill_parent" >
</TextView>
</LinearLayout>
</ScrollView>

Bye for now.
/r0b

No comments:

Post a Comment