Tuesday, February 12, 2013

NumberFormat parse and format methods

format
The format method converts a number to a String representation, according to a given Locale.
Eg.

NumberFormat nf = NumberFormat.getInstance(Locale.GERMAN);
double d = 123.57;
System.out.println(nf.format(d));

This will print 123,57

parse
The parse method uses a String to be converted to a Number, for a given Locale.

NumberFormat fr = NumberFormat.getInstance(Locale.FRANCE);

try {
  String s = “123,45”;
  System.out.println(fr.parse(s));
}catch(ParseException e) {
  e.printStackTrace();
}

This will print 123.45

The parse method only parses the beginning of a string. After it reaches a character that cannot be parsed, the parsing stops and the value is returned.

E.g

NumberFormat nf = NumberFormat.getInstance();
try{
  String one = “456abc”;
  System.out.println(nf.parse(one));
}catch(ParseException e) {
  e.printStackTrace();
}

This will print 456


setMaximumFractionDigits
Attention to the setMaximumFractionDigits, that is not a regular truncate function, but instead, it rounds the number up or down when truncating.
E.g
NumberFormat nf = NumberFormat.getInstance();
nf.setMaximumFractionDigits(4);
nf.setMinimumFractionDigits(2);

String a = nf.format(3.1415926);
String b = nf.format(2);

System.out.println(a);
System.out.println(b);


This will print:
3,1416
2,00

No comments:

Post a Comment