Shnatta
Shnatta

Reputation: 35

Can't change Integer to Double, and this cause my code to fail

I'am trying to divide x by 9, and when x divided by 9 returns something bigger than 1, I proceed with my code. But what if x is 10? 10 divided by 9 returns 1,1 which means that you can only make one item and the 0,1 should be returned to you.

Example: I have 64 of item a and try to create another item b which needs at least 9 of item a to create one item b. If we divide 64 by 9 it returns 7,1 which means that we can get a max of 7 item b. The 0,1 gives me 0.0 when i try to round it up with Math.ceil().

Anyone know how I can get 0,1 of 64 / 9 and round it up to one?

This is what I've tried:

Integer getIronBlocks = ironIngots / 9;
Integer getGoldIngots = goldNuggets / 9;
double ironIngotLeft = Math.ceil(getIronBlocks);
double goldNuggetLeft = Math.ceil(getGoldIngots);

I already know the issue of this code, but don't know how to fix it. Lets say ironIngots = 64 and we divide it by 9 we get 7 not 7,1. Changing Integer getIronBlocks to Double getIronBlocks will raise an error by IntelliJ

Upvotes: 1

Views: 58

Answers (2)

Juan
Juan

Reputation: 5589

The problem is that by using Integer class, the decimals of the result are lost.

So what you end up doing is rounding up 0 which will give 0 as a result.

Use BigDecimal if you want accuracy in the operation. Or Double, but Double has binary operations issue with accuracy.

Upvotes: 0

Florent Amaridon
Florent Amaridon

Reputation: 146

you need use double to store the result and divide by double.

    int ironIngots = 10;
    double getIronBlocks = ironIngots / 9.0;
    System.out.println("result : "+ getIronBlocks); // ---> 1.111111

https://ideone.com/Yz4yBO

If you divide by an int the result is an int.

Upvotes: 1

Related Questions