Format and parse an integer

Problem:

You want to format and parse integer values.

Solution:

The Java NumberFormat class makes formatting and parsing a number is localized manner easy and efficient.  Simple specify the locale when retrieving the NumberFormat instance.

 

To format and parse a number in Hindi:

//Get a locale.  Hindi in India here.
ULocale hindi = new ULocale("hi_IN");
//Get an instance of an integer format.
NumberFormat nf = NumberFormat.getIntegerInstance(hindi);
//format and output.  The decimal is cut off and rounded.
String f = nf.format(1234234234.556);
System.out.println(f);

//Parse the value.  We must handle the potential ParseException
try {
    System.out.println(nf.parse("१,२३,४२,३४,२३५"));
} catch (ParseException e) {
    e.printStackTrace();
}

 


The output:

१,२३,४२,३४,२३५
1234234235