Sunday, July 27, 2014

Display formated currency using DecimalFormat.getCurrencyInstance(locale)

This example show how to display currency for a specified locale, using DecimalFormat.getCurrencyInstance(locale).format().

   


package com.example.androidstringformat;

import java.text.DecimalFormat;
import java.text.NumberFormat;
import java.util.Locale;

import android.support.v7.app.ActionBarActivity;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemSelectedListener;
import android.widget.ArrayAdapter;
import android.widget.Spinner;
import android.widget.TextView;
import android.os.Bundle;

public class MainActivity extends ActionBarActivity {
 
 TextView textOut;
 TextView localeInfo;
 
 Spinner spAvailableLocale;
 Locale[] availableLocales;
 
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        
     textOut = (TextView)findViewById(R.id.printout);
     localeInfo = (TextView)findViewById(R.id.localeinfo);
     
     //get installed locales
     availableLocales = Locale.getAvailableLocales();
     spAvailableLocale = (Spinner)findViewById(R.id.spavlocale);
     
     ArrayAdapter<Locale> adapter = 
      new ArrayAdapter<Locale>(this, 
       android.R.layout.simple_spinner_item, 
       availableLocales);
     adapter.setDropDownViewResource(
       android.R.layout.simple_spinner_dropdown_item);
     spAvailableLocale.setAdapter(adapter);
     spAvailableLocale.setOnItemSelectedListener(onItemSelectedListener);
    }

    OnItemSelectedListener onItemSelectedListener =
     new OnItemSelectedListener(){

   @Override
   public void onItemSelected(AdapterView<?> parent, View view,
     int position, long id) {
    Locale locale = (Locale)parent.getItemAtPosition(position);
    localeInfo.setText(String.format(
     "DisplayCountry: %s\nDisplayLanguage: %s\nDisplayName: %s\n\n", 
     locale.getDisplayCountry(), 
     locale.getDisplayLanguage(),
     locale.getDisplayName()));
    
    NumberFormat numberFormat = DecimalFormat.getCurrencyInstance(locale);
    String strNum = numberFormat.format(12345.6789f);
    
    textOut.setText(strNum);
   }

   @Override
   public void onNothingSelected(AdapterView<?> arg0) {}
     
    };
    
}


Usign the same layout as in last example of "Display Date formated using String.format() with Locale".

No comments: