How to use NumberFormat Class in Android? – Rounding a number in android, formatting, getting decimal values etc in android.

By | September 25, 2012
package com.coderzheaven.numberformattest;
 
import java.text.DecimalFormat;
import java.text.NumberFormat;
import java.util.Locale;
import android.app.Activity;
import android.os.Bundle;
import android. widget. TextView;
 
public class MainActivity extends Activity {
     
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
     
        TextView tv = new TextView(this);
        tv.setPadding(10, 10, 10, 10);
        NumberFormat numberFormat  = new DecimalFormat("##");
        String str = numberFormat.format(-01234.567);         // -1235
        tv.setText(str + "\n\n");
  
        str = numberFormat.format(00);                 // 0
        tv.append(str + "\n\n");
  
        numberFormat = new DecimalFormat("##00");
        str = numberFormat.format(0);                 // 00
        tv.append(str + "\n\n");
  
        numberFormat = new DecimalFormat(".00");
        str = numberFormat.format(-.4567);             // -.46
        tv.append(str + "\n\n");
  
        numberFormat = new DecimalFormat("0.000");
        str = numberFormat.format(-.34567);             // -0.346
        tv.append(str + "\n\n");
  
        numberFormat = new DecimalFormat("#.######");
        str = numberFormat.format(-012.34567);         // -12.34567
        tv.append(str + "\n\n");
  
        numberFormat = new DecimalFormat("#.000000");
        str = numberFormat.format(-1234.567);         // -1234.567000
        tv.append(str + "\n\n");
         
        numberFormat = new DecimalFormat("#,###,###");
        str = numberFormat.format(-01234567.890);      // -1 234 568
        tv.append(str + "\n\n");
  
        numberFormat = new DecimalFormat("'text'#");
        str = numberFormat.format(+1234.567);         // text1235      
        tv.append(str + "\n\n");
  
        // Exponential notation
        numberFormat = new DecimalFormat("00.00E0");
        str = numberFormat.format(-012345.67);         // -12.35E2     
        tv.append(str + "\n\n");
         
        //  set locale format
        // FRANCE  locale
        Locale locale = Locale.FRANCE;
        str = NumberFormat.getNumberInstance(locale).format(-123456.789);  // -123 456,789
        tv.append(str + "\n\n");
         
        setContentView(tv);
         
    }
}

NumberFormat

One thought on “How to use NumberFormat Class in Android? – Rounding a number in android, formatting, getting decimal values etc in android.

  1. SAUL MEYER

    This rounds 12.345 to 12.34
    Excel rounds 12.345 to 12.35
    Which is correct?

    Reply

Leave a Reply

Your email address will not be published. Required fields are marked *