How to convert Double to Int when dividing two Doubles and multiplying the Double quotient by Int?

Tags:



I am working on the program below. How do you calculate totalCostPerMiles = (numMiles / milesPerGallon) * price; when totalCostPerMiles is a int, numMiles and milesPerGallon are doubles, and price is a int to get the calculated value?

Suppose milesPerGallon = 30;, numMiles = 15;, and price = 400;.

I need numMiles / milesPerGallon to output 0.5 instead of 0 and totalCostPerMiles to output 200 instead of 0.

All variables storing measured values must be doubles and all variables storing monetary values must be integers.

import java.util.Scanner;

public class RoadTrip {
 public static void main(String[] args) {
  
  int price, budgetPrice,
  priceInDollars, priceInCents, priceInDollarsBudget, priceInCentsBudget,
  totalCostPerMiles, dollars, cents;
  
  double milesPerGallon, numMiles, totalMilePerGall;
  
  Scanner stdin = new Scanner(System.in);
  
  milesPerGallon = stdin.nextDouble(); 
  
  numMiles = stdin.nextDouble(); 
  
  price = stdin.nextInt(); 
  
  budgetPrice = stdin.nextInt(); 
  
  
  
  
  totalCostPerMiles = (numMiles / milesPerGallon) * price; //produces error

Answer

math ops are always binary (so, 2 arguments. ‘a+b+c’ is not a 3-way addition; it’s shorthand for (a+b)+c – 2 nested binary operations.

If either ‘side’ of the binary operation is a double, then first the other number (int, long, float, byte, char, short, doesn’t matter) is converted to a double, then the operation is done, and the result is a double.

So, (numMiles / milesPerGallon) is an expression of type double.

Then, you do that (so, a double), times an int: that * price. price is an int, but double*int is done by first converting that int to a double. Thus, the entire result is, itself, a double.

You then try to assign that to an int, and that’s where the problem occurs: You can’t do that, because java has no idea what you want. Should 6.5 become 6, or 7? What about 1.239e123?

You can choose what to do. The simplest way is the ‘lop off rounding’ mode, which lops off the fraction (so, round down.. unless the number is negative, in which case that’d round up):

totalCostPerMilis = (int) ((numMiles / milesPerGallon) * price);

you can even use this and go with different rounding options: Add 0.5 to the mix and now it’s rounding to nearest, with x.5 rounding up.

Other stuff can be found with e.g. Math.round().



Source: stackoverflow