This week's giveaway is in the Spring forum.We're giving away four copies of Microservices Testing (Live Project) and have Chris Love & Andres Sacco on-line!See this thread for details.
Win a copy of Microservices Testing (Live Project) this week in the Spring forum!
programming forums Java Mobile Certification Databases Caching Books Engineering Micro Controllers OS Languages Paradigms IDEs Build Tools Frameworks Application Servers Open Source This Site Careers Other Pie Elite all forums
this forum made possible by our volunteer staff, including ...
Marshals:
• Campbell Ritchie
• Tim Cooke
• Ron McLeod
• Jeanne Boyarsky
• Paul Clapham
Sheriffs:
• Liutauras Vilda
• Henry Wong
• Devaka Cooray
Saloon Keepers:
• Tim Moores
• Stephan van Hulst
• Tim Holloway
• Al Hobbs
• Carey Brown
Bartenders:
• Piet Souris
• Mikalai Zaikin
• Himai Minh

# String to double losing decimal places

Ranch Hand
Posts: 42
• Number of slices to send:
Optional 'thank-you' note:
Why does the following occur? A double can hold these numbers can't it?

source = "1234567890123.1234";
dvalue = Double.parseDouble(source);
result = formatter.format(dvalue);
out.print(source + " = " + result + br);
//gives1234567890123.1234 = 1,234,567,890,123.1233

source = "12345678901234.1234";
dvalue = Double.parseDouble(source);
result = formatter.format(dvalue);
out.print(source + " = " + result + br);
//gives12345678901234.1234 = 12,345,678,901,234.123

source = "123456789012345.1234";
dvalue = Double.parseDouble(source);
result = formatter.format(dvalue);
out.print(source + " = " + result + br);
//gives123456789012345.1234 = 123,456,789,012,345.12

author
Posts: 23924
142
• Number of slices to send:
Optional 'thank-you' note:
As you probably figured out by now, floating point numbers have restrictions in both range and precision.

If you exceed the range, Java will complain. If you exceed the precision, it will just round it off.

Henry

author
Posts: 14112
• Number of slices to send:
Optional 'thank-you' note:
And if you need more precision, you should take a look at the BigDecimal class.

 Did you see how Paul cut 87% off of his electric heat bill with 82 watts of micro heaters?