Why java converts double to exponential form

kwan_ah picture kwan_ah · Dec 19, 2012 · Viewed 8.4k times · Source

I have a problem. In my jsp page I have a textfield which accepts monetary value. When I enter a value such as 66777764 it becomes 6.6777764E7 in my textfield whenever there is a validation error. I know this won't affect the value saved in the database but I think its misleading/confusing to the user. Please help. Thanks in advance.

Answer

Aviram Segal picture Aviram Segal · Dec 19, 2012

It seems you keep your number as double so 66777764 is actually 66.777764.0 and it displays what you got.

You can use DecimalFormat to format the display of the number as you wish, for example:

double d = 1.234567;
DecimalFormat df = new DecimalFormat("#.##");
System.out.print(df.format(d)); // will print 1.23

This will display the number with 2 digits after the point (66777764.00), there are many options for the format, check the documentation for info.