Please justify the output for the below code.
Code:
import java.text.NumberFormat; import java.text.ParseException;
public class Number_format_Demo {
/**
* @param args
* @throws ParseException
*/
public static void main(String[] args) throws ParseException {
NumberFormat nf=NumberFormat.getInstance();
nf.setMaximumFractionDigits(1);
String s[]={"111.234","222.5678"};
for(String st:s)
System.out.println(nf.parse(st));
}
}
Output:
111.234 222.5678
Question:
If we have set the maximum digits as 3 then how come the second line of output is correct?
The method setMaximumFractionDigits is used with the method "format" not with the method "parse". Moreover, float datatypes can be formatted not the String datatype.
So, the correct program could be as follows.
import java.text.NumberFormat; import java.text.ParseException;
public class Number_format_Demo {
}