Search code examples
javaparsingdecimalformat

How to format a double without converting it into string type


I want values like

1,
1.0,
0 

to be formatted to

1.00,
1.00,
0.00

I'm using the following code,

Double stringToNumber=Double.parseDouble("3");
DecimalFormat toTheFormat = new DecimalFormat("0.00");
toTheFormat.format(stringToNumber)

.format returns a string and if I parse using Double.parseDouble() method.

I lose the precision, i,e 3.00 becomes 3.0 again.How to solve this?


Solution

  • Would this work? I have made changes

        public class Tester {
        public static void main (String[] args) {
            double d = 1;
            NumberFormat numFormat = NumberFormat.getInstance();
            numFormat.setMaximumFractionDigits(3);
            numFormat.setMinimumFractionDigits(2);
            System.out.println(numFormat.format(d));
        }
    }