0

I'm trying to create a Money Maker that based on the user's input it gathers how much you need of each cent.

Gold Coins = .10 , Silver = .05 & Bronze = .01

I've tried a couple of things to debug my code and notices when my remainder fraction is close to a number it will give me a bug e.g. user inputs .65 when using .65 % .10 i get .049999999... hence when going through the silver value it doesn't take it into consideration and just pushes it out to the bronze coins.

System.out.println("What amount would you like to convert");

String stringInput = userInput.readLine();

double amountToConvert = Double.parseDouble(stringInput);

double goldValue = .10;
double goldCoins = Math.floor(amountToConvert / goldValue);
double remainder = amountToConvert % goldValue; // here if a value is super close to, and it will not round it and pass it over to Bronze coins incorrectly.

double silverValue = .05;
remainder = remainder % silverValue;

I've already tried Math.ceil and it just rounds up the fraction as a whole and that's not what I need.

Mark Rotteveel
  • 100,966
  • 191
  • 140
  • 197
  • 2
    Do not use floating point number types like `float` or `double` for money values. Work with "cent" values instead by using `int` or `long` types. – Progman Jan 15 '22 at 11:48

1 Answers1

0

This may not be your direct answer. But as an alternative you can simply work with integer values between 1 to 100. If you need can divide results to 100.

User input 65 leads 6 gold and 1 silver.

  public static void main(String[] args) {
        System.out.println("What amount would you like to convert");
        String stringInput = "65";

        int amountToConvert = Integer.parseInt(stringInput);


        int goldValue = 10;
        int goldCoins = amountToConvert / goldValue;
        System.out.println(goldCoins);
        int remainder = amountToConvert % goldValue; // here if a value is super close to, and it will not round it and pass it over to Bronze coins incorrectly.

        //System.out.println(remainder);

        int silverValue = 5;
        remainder = remainder / silverValue;
        System.out.println(remainder);
    }
Majid Hajibaba
  • 3,105
  • 6
  • 23
  • 55