This week's book giveaways are in the Angular and TypeScript and Web Services forums.
We're giving away four copies each of Programming with Types and The Design of Web APIs and have the authors on-line!
See this thread and this one for details.
Win a copy of Programming with Types this week in the Angular and TypeScript forum
or The Design of Web APIs in the Web Services 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 all forums
this forum made possible by our volunteer staff, including ...
Marshals:
  • Campbell Ritchie
  • Liutauras Vilda
  • Bear Bibeault
  • Paul Clapham
  • Jeanne Boyarsky
Sheriffs:
  • Junilu Lacar
  • Knute Snortum
  • Henry Wong
Saloon Keepers:
  • Ron McLeod
  • Tim Moores
  • Stephan van Hulst
  • Tim Holloway
  • Carey Brown
Bartenders:
  • Frits Walraven
  • Joe Ess
  • salvin francis

BigDecimal

 
Greenhorn
Posts: 10
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I have to retain the exact value of a Double and convert it into a string.

Double value = 105312453566.35363465;

I tried doing a toString() on the above Double value... but it returns me an output 1.0531245356635364E11



Hence I tried converting it into a BigDecimal format using the below code... so that I can retain the exact value..

BigDecimal newValue = new BigDecimal(value);
System.out.println("BigDecimal Value: " + newValue);

But the output which I get is like this :

BigDecimal Value: 105312453566.3536376953125

which is again not what I want.


How can I get the exact value?
 
Rancher
Posts: 43011
76
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
That number has 20 digits, and doubles simply do not have that much accuracy. Around 16 digits is the most number of accurate digits that's possible. See #20 in the http://faq.javaranch.com/java/JavaBeginnersFaq for some background information.

The solution to your problem is to use the BigDecimal(String) constructor. It retains all digits of its parameter.
 
Ranch Hand
Posts: 95
Scala Java
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I agree with Ulf.
An another approach is to multiply the double value for a number (like 1000) that makes the double an int.
 
Ulf Dittmer
Rancher
Posts: 43011
76
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
An int has even less precision than a double (around 10 digits), and a long has around 19, so neither of those would work in this case.
 
This cake looks terrible, but it tastes great! Now take a bite out of this tiny ad:
Java file APIs (DOC, XLS, PDF, and many more)
https://products.aspose.com/total/java
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!