type double multiplication errors

how to work around inherent multiplication errors with type double

Page 1 of 1

1 Replies - 6368 Views - Last Post: 09 September 2008 - 10:36 PM Rate Topic: -----

#1 woobear  Icon User is offline

  • New D.I.C Head

Reputation: 0
  • View blog
  • Posts: 5
  • Joined: 21-March 08

type double multiplication errors

Post icon  Posted 09 September 2008 - 10:19 PM

i ran into this error while doing checks on my completed project.
the program asks for an amount of money then gives back the smalest number of coins needed to equal that amount of money.
in order to convert my input from type doubl to type int without loosing the info to the right of the decimal i first multiply by 100, then do my conversion.
however certin numbers give back incorect awnsers.

0.07 should equal 7.00 but doesnt.
also 2100.01 gives the wrong awnser also.. any 2100 number with an odd hundredths number is wrong

here is the isolated code.

import java.util.Scanner;

public class coinsMultiplyError
{
	public static void main(String[] args)
		{
			Scanner keyboard = new Scanner(System.in);
			
			System.out.println("Please enter amount of monney");
			
			double total = keyboard.nextDouble();//input from user
						
			total=total*100;
			System.out.println(total);
			}
			}


is there any other way to isolate the decimal numbers and convert to int?
i tryed keyboard.useDeliniator(".") as a substitute for useing a space between the dollars and change.it would compile but then iit would yell at me when i tryed to run it.

Is This A Good Question/Topic? 0
  • +

Replies To: type double multiplication errors

#2 pbl  Icon User is offline

  • There is nothing you can't do with a JTable
  • member icon

Reputation: 8334
  • View blog
  • Posts: 31,858
  • Joined: 06-March 08

Re: type double multiplication errors

Posted 09 September 2008 - 10:36 PM

The easiest way:

convert to an int and them / 100

double total;
int intTotal = (int) (total * 100);
double rounded = intTotal / 100.0;
Was This Post Helpful? 0
  • +
  • -

Page 1 of 1