• Post Reply Bookmark Topic Watch Topic
  • New Topic
programming forums Java Mobile Certification Databases Caching Books Engineering Micro Controllers OS Languages Paradigms IDEs Build Tools Frameworks Application Servers Open Source This Site Careers Other Pie Elite all forums
this forum made possible by our volunteer staff, including ...
Marshals:
  • Campbell Ritchie
  • Jeanne Boyarsky
  • Ron McLeod
  • Paul Clapham
  • Liutauras Vilda
Sheriffs:
  • paul wheaton
  • Rob Spoor
  • Devaka Cooray
Saloon Keepers:
  • Stephan van Hulst
  • Tim Holloway
  • Carey Brown
  • Frits Walraven
  • Tim Moores
Bartenders:
  • Mikalai Zaikin

NumberFormat question

 
Ranch Hand
Posts: 46
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
This code is from the Whizlabs simulator:

Question... why do you need two instance of NumberFormat, one with a locale and one without? Can't I just use the Italian Locale instance to parse and format? Thanks
_______________________________________________
import java.util.*;
import java.text.*;


class Locale2 {
public static void main( String[] args ) {
NumberFormat i = NumberFormat.getInstance(Locale.ITALY);
NumberFormat n = NumberFormat.getInstance();

try {
Number val = i.parse(args[0]);
String s=n.format(val);

System.out.println(s);
}
catch (ParseException e) { }

}
}
 
Sheriff
Posts: 11343
Mac Safari Java
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
The parse method takes a String, and returns a Number based on how it's understood to be formatted (what locale applies). The format method takes some type of value (it's overloaded to accept primitives or an Object) and returns a String that's formatted for the given locale.

The code above parses a String that's formatted in the Italian locale, but outputs a String formatted in the default locale. So it's reading it based on one locale, but outputting based on a different locale (unless your default is Italian).

So, for example, if I enter an argument of 12.345, this is parsed in the Italian locale, using the period as a separator, so the value is twelve-thousand, three-hundred forty-five. The using my default locale (US), this is output on my machine as 12,345.
 
reply
    Bookmark Topic Watch Topic
  • New Topic