Results 1 to 5 of 5
Thread: Problem multiplying a double
 10092012, 06:02 PM #1Member
 Join Date
 Oct 2012
 Posts
 2
 Rep Power
 0
Problem multiplying a double
Hello
I'm pretty new to Java and was practising by putting together a calculator which would work out how many of each note and coin demonination make up the change given with a certain monetary total. eg £1.22
It seems to work for EVERY starting figure other than 19.99. I have narrowed down the cause of the problem. It seems to be coming from the multiplication used to convert the figure from pounds to pence (or dollors to cents etc depending on where you're from).
Java Code:double change; change = 19.99 * 100; System.out.println(change);
This appears to happen for 16.99, 17.99 and 18.99. Every other number seems to be worked out correctly ie 15.99 produces the desired figure of 1599.
Does anyone have any idea what is going on here and how this can be resolved.
Kind regards
 10092012, 06:05 PM #2Moderator
 Join Date
 Apr 2009
 Posts
 13,541
 Rep Power
 27
Re: Problem multiplying a double
Floating points are not precise, anymore than 0.33333 is the same as 1/3.
Or, you could just read Goldberg.Please do not ask for code as refusal often offends.
** This space for rent **
 10092012, 06:11 PM #3
 Join Date
 Sep 2008
 Location
 Voorschoten, the Netherlands
 Posts
 14,422
 Blog Entries
 7
 Rep Power
 28
Re: Problem multiplying a double
Welcome to the wonderful world of floating point numbers; the number 0.1 can't be represented by the IEEE754 floating point number format system, that's why you get those funny results. Not everything is lost though: add 1/2 a penny to the result and then take the integer part, e.g. (int)(1998.99999999998+0.5)
kind regards,
JosBuild a wall around Donald Trump; I'll pay for it.
 10092012, 06:12 PM #4Member
 Join Date
 Oct 2012
 Posts
 2
 Rep Power
 0
Re: Problem multiplying a double
Thank you for the quick reply
 10102012, 09:51 AM #5Moderator
 Join Date
 Apr 2009
 Posts
 13,541
 Rep Power
 27
Similar Threads

Casting problem (Type object)
By FiasseKrystella in forum New To JavaReplies: 1Last Post: 03042012, 08:11 AM 
Casting Problem
By nathandelane in forum Advanced JavaReplies: 4Last Post: 10102011, 07:09 PM 
how to read an integer of DOUBLE datatype with type casting
By amrmb09 in forum Advanced JavaReplies: 2Last Post: 12142010, 08:01 PM 
Casting problem
By Lil_Aziz1 in forum New To JavaReplies: 2Last Post: 05292010, 07:13 PM 
Casting problem
By John_28 in forum New To JavaReplies: 6Last Post: 05142008, 11:29 AM
Bookmarks