🚀 go-pugleaf

RetroBBS NetNews Server

Inspired by RockSolid Light RIP Retro Guy

Article View: borland.public.jbuilder.java.language
Article #16498

Re: Math calculations

#16498
From: Steve Schafer (TeamB)
Date: Tue, 16 Feb 1999 00:00
43 lines
2510 bytes
On Tue, 16 Feb 1999 13:26:40 -0500, "Kerry Helmer"
<khelmer@parlorcity.com> wrote:

>I am new to Java and I'm having a rough time understanding the math
>calculations.  Here is an  examples of one of the problems that I'm having.
>
>double tender = 99.99
>centsRemain = (int)(100.00d * (tender % 1.00d));
>
>The centsRemain variable ends up being 98 instead of 99.
>When I tried to check out the problem by doing the following code:
>System.out.println ((tender % 1.00d));
>This returns 0.9899999999999949 instead of .99  Can someone help explain to
>me what I'm doing wrong?

The only thing you're doing wrong is assuming that calculations
involving floating-point numbers (float and double in Java) are exact.
In fact, all floating-point numbers are approximations, and must be
treated that way. In the same way that 1/3 cannot be exactly
represented as a finite decimal fraction, most decimal values cannot
be exactly represented as finite binary fractions (which is the
internal representation of floating-point values).
 
In your case, since it looks like you're dealing with money, the
solution is to internally maintain your values in cents, or whatever
the fractional unit is for your currency, and then scale the values
for input and output only.

In Windows, there is a standard Currency type which is a 64-bit
integer that has been scaled to assume 4 decimal places. (Thus a value
stored internally as 123456 is interpreted on output as 12.3456.)
While you can't use that type directly in your Java code, you can at
least emulate it with a long. That will allow you to handle values of
up to 1.8E+15 dollars or pounds or colones or whatever.

>Does anybody have some rules to follow that would help me when performing
>math operations?

There's just one basic rule: Assume that any floating-point
calculation you perform will involve round-off errors. Always take
that into consideration, and you won't go wrong.

-Steve
Technical Details
Message-ID: <37ddcd4b.752218449@90.0.0.40>
Path: arc1-ca.pugleaf.net!unknown!not-for-mail
References: <7acd6l$6vc20@forums.borland.com>

Show Full Headers
Complete Article Headers
X-Google-Language: ENGLISH,ASCII-7-bit
X-Google-Thread: f74b3,587049a5d7e832c
X-Google-Attributes: gidf74b3,public
From: pandeng@telepath.com (Steve Schafer (TeamB))
Subject: Re: Math calculations
Date: 1999/02/16
Message-ID: <37ddcd4b.752218449@90.0.0.40>
X-Deja-AN: 445050476
Content-Transfer-Encoding: 7bit
References: <7acd6l$6vc20@forums.borland.com>
Content-Type: text/plain; charset=us-ascii
Organization: TeamB
Mime-Version: 1.0
Reply-To: pandeng@telepath.com
Newsgroups: borland.public.jbuilder.java.language