This week's book giveaway is in the Agile and other Processes forum.
We're giving away four copies of The Mikado Method and have Ola Ellnestam and Daniel Brolund on-line!
See this thread for details.
The moose likes Beginning Java and the fly likes BigDecimal Big Moose Saloon
  Search | Java FAQ | Recent Topics
Register / Login


Win a copy of The Mikado Method this week in the Agile and other Processes forum!
JavaRanch » Java Forums » Java » Beginning Java
Reply Bookmark "BigDecimal" Watch "BigDecimal" New topic
Author

BigDecimal

Ashutosh Deo
Greenhorn

Joined: Jul 12, 2006
Posts: 10
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?
Ulf Dittmer
Marshal

Joined: Mar 22, 2005
Posts: 35241
    
    7
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.


Android appsImageJ pluginsJava web charts
Andre Brito
Ranch Hand

Joined: Dec 13, 2007
Posts: 95

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
Marshal

Joined: Mar 22, 2005
Posts: 35241
    
    7
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.
 
I agree. Here's the link: http://zeroturnaround.com/jrebel - it saves me about five hours per week
 
subject: BigDecimal
 
Similar Threads
regarding bigdecimal.divide problem
Trouble with BigDecimal and Double
What actual Double.toString(double d) does?
Convert String to BigDecimal
query about double addition