setMaximumDigits method of NumberFormat class

57 views Asked by At

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?

1

There are 1 answers

0
VISHAL SAXENA On

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 {

/**
 * @param args
 * @throws ParseException 
 */
public static void main(String[] args) throws ParseException {
    NumberFormat nf=NumberFormat.getInstance();
    nf.setMaximumFractionDigits(1);
    Float s[]={111.234f,222.5678f};
    for(Float st:s)
        System.out.println(nf.format(st));

}

}