Sunday 15 January 2012

Playing with double datatype using Java

Do you guess the output values of the following code snippets (in  Java) ? .


                        double d5 =99999.99;
                        double d6 =999999.99;
                        double d7 =9999999.99;
                        double d8 =99999999.99;
                        double d9 =999999999.99;
                        double d10=9999999999.99;

                        System.out.println("d5 ="+d5);
                        System.out.println("d6 ="+d6);
                        System.out.println("d7 ="+d7);
                        System.out.println("d8 ="+d8);
                        System.out.println("d9 ="+d9);
                        System.out.println("d10="+d10);

Here is the output:




d5 =99999.99
d6 =999999.99
d7 =9999999.99
d8 =9.999999999E7
d9 =9.9999999999E8
d10=9.99999999999E9

Have you noticed the values of d8, d9 and d10?. The output value is in  E (exponential) format. Java is internally doing this conversion while convert the datatype double to String.  If the value is  greater than or equal to 10-3 but less than 107, then the output will be normal. Otherwise the value will be in Exponential.

To print the values all in normal format, use the "java.text.DecimalFormat" class. Check the following code snippet.


                        DecimalFormat d = new DecimalFormat("##.##");
                        System.out.println("d5 ="+d.format(d5));
                        System.out.println("d6 ="+d.format(d6));
                        System.out.println("d7 ="+d.format(d7));
                        System.out.println("d8 ="+d.format(d8));
                        System.out.println("d9 ="+d.format(d9));
                        System.out.println("d10="+d.format(d10));
The output is


d5 =99999.99
d6 =999999.99
d7 =9999999.99
d8 =99999999.99
d9 =999999999.99
d10=9999999999.99

Refer the following URL to get the more details about the Double,.

No comments:

Post a Comment