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!
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
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
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
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
jQuery Eclipse IDE Firefox Browser VI Editor C++ Chrome Java Linux Windows
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
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
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
And if you need more precision, you should take a look at the BigDecimal class.
reply
    Bookmark Topic Watch Topic
  • New Topic