wood burning stoves
The moose likes Java in General and the fly likes bigInteger to float or double Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Java » Java in General
Bookmark "bigInteger to float or double" Watch "bigInteger to float or double" New topic

bigInteger to float or double

chop ficaro
Ranch Hand

Joined: May 02, 2010
Posts: 30
ive got a java.math.bigInteger in the DENOMINATOR of a function, and i need it to return a float. how do i do this while keeping as much accuracy as possible (the denominator could be as large as 10^80)
Rob Spoor

Joined: Oct 27, 2005
Posts: 20273

As soon as you turn it into a float you've lost quite a bit of accuracy already. That's because float only has 32 bits in which to store both the integer and the decimal part. double is better but still limited. The only way to maintain your accuracy is to keep using BigInteger.

How To Ask Questions How To Answer Questions
Mike Simmons
Ranch Hand

Joined: Mar 05, 2008
Posts: 3028
This is true. However if indeed you have to return a float (perhaps because you're implementing a method that returns a float, and can't edit the original interface) then the question was how to do this with as much accuracy as possible. Under these conditions I would simply use BigInteger's doubleValue() method, perform the division, and then cast the result to float. There may be other ways equally accurate, but there isn't really any way that's more accurate. You should get nearly the same result by converting to floatValue() and then dividing - but it's a little more accurate if you use the more precise value (a double) for as long as you can.
I agree. Here's the link: http://aspose.com/file-tools
subject: bigInteger to float or double
jQuery in Action, 3rd edition