Article View: borland.public.jbuilder.java.language
Article #8537Re: double division rounding error
From: John McGrath TeamB
Date: Tue, 13 Mar 2001 04:33
Date: Tue, 13 Mar 2001 04:33
32 lines
2094 bytes
2094 bytes
On 12 Mar 2001 14:11:43 -0800, Ron Reynolds wrote:
> this i don't get, especially since the numbers are so simple.
> the following code:
> double d1 = 2.05, d2 = 0.05;
> System.out.println("d1/d2 = " + d1/d2);
> produces:
> d1/d2 = 40.99999999999999
> if i cast the result to "float" i can get 41.0, which is nice,
> but my question is why this sort of rounding error pops up with
> such low-precision numbers and what's the accepted way of
> handling this sort of problem?
That is how floating point numbers work, not only in Java but in most
other languages. While your numbers divide nicely in decimal, that is
not the case with floating point values, which are encoded as binary
numbers.
The issue is how you format the numbers. You are implicitly using the
toString() method, which displays all of the significant digits of the
number. There are other methods for formatting numbers that should
give you the results you are looking for. Take a look at the java.util
DecimalFormat class.
--
Regards,
John McGrath [TeamB]
---------------------------------------------------
Before sending me e-mail, please read:
http://www.JPMcGrath.net/newsgroups/e-mail.html
Technical Details
Message-ID:
<MPG.15176c9b4c89668398a05b@forums.borland.com>Path:
arc1-ca.pugleaf.net!supernews.google.com!sn-xit-03!supernews.com!news-out.usenetserver.com!news-out-sjo.usenetserver.com!feed2.onemain.com!feed1.onemain.com!newsfeeds.belnet.be!news.belnet.be!newsfeed00.sul.t-online.de!newsfeed01.sul.t-online.de!t-online.de!bornews.borland.com!not-for-mailReferences:
<3aad499f$1_2@dnews>Show Full Headers
Complete Article Headers
X-Google-Language: ENGLISH,ASCII-7-bit X-Google-Thread: f74b3,1db527391e14d00c X-Google-Attributes: gidf74b3,public X-Google-ArrivalTime: 2001-03-12 20:44:04 PST Path: arc1-ca.pugleaf.net!supernews.google.com!sn-xit-03!supernews.com!news-out.usenetserver.com!news-out-sjo.usenetserver.com!feed2.onemain.com!feed1.onemain.com!newsfeeds.belnet.be!news.belnet.be!newsfeed00.sul.t-online.de!newsfeed01.sul.t-online.de!t-online.de!bornews.borland.com!not-for-mail From: John McGrath [TeamB] <ng-b@JPMcGrath.net> Newsgroups: borland.public.jbuilder.java.language Subject: Re: double division rounding error Date: Mon, 12 Mar 2001 23:33:56 -0500 Organization: Another Netscape Collabra Server User Lines: 32 Message-ID: <MPG.15176c9b4c89668398a05b@forums.borland.com> References: <3aad499f$1_2@dnews> NNTP-Posting-Host: dslcv1-60.fast.net X-Newsreader: MicroPlanet Gravity v2.30