wood burning stoves 2.0*
The moose likes Beginning Java and the fly likes Decimal place result Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login


Win a copy of EJB 3 in Action this week in the EJB and other Java EE Technologies forum!
JavaRanch » Java Forums » Java » Beginning Java
Bookmark "Decimal place result" Watch "Decimal place result" New topic
Author

Decimal place result

henry akoma
Greenhorn

Joined: May 17, 2005
Posts: 21
hi guys,
some colleagues and i were writting a calculator program, but the result of some of our calculations were giving approximate answers and not the exact one.for example:


subtraction gave -0.100000024 instead of -0.1.

please can anyone help us with what to do to get the correct answer and may be decimal place
Ulf Dittmer
Marshal

Joined: Mar 22, 2005
Posts: 39541
    
  27
floats are inherently limited in their precision, and some numbers just can't be expressed precisely using them. "0.1" is such a number, as is "0.9". Using doubles makes things a bit better (around 14 exact decimals instead of 7 or so), but the basic problem is the same. (If you're interested in the gory details, read up on What Every Computer Scientist Should Know About Floating-Point Arithmetic.)

If you require exact floating point arithmetic, you can use the java.math.BigDecimal class.
[ August 09, 2005: Message edited by: Ulf Dittmer ]

Ping & DNS - updated with new look and Ping home screen widget
Stuart Gray
Ranch Hand

Joined: Apr 21, 2005
Posts: 410
There are well known problems with floating point arithmetic. You could try BigDecimal in the java.math package.
 
With a little knowledge, a cast iron skillet is non-stick and lasts a lifetime.
 
subject: Decimal place result
 
Similar Threads
[floats and doubles] float f = 80/9; // f=8.0!!
Decimals not converting to correct fractions
related to arithmetic operations on datatype.
Dividing Ints
assiging int to float