boxslide15
boxslide15

Reputation: 1

How to covert a double to an int

I'm trying to convert a double to an int but I don't get my expected results. Can someone help me? Here's my code. My expected output is 21 but I keep getting 21.0.

double costItem2 = 32.55;
int budget2 = 713;
double totalItem2 = budget2 / costItem2;
totalItem2 = (int) totalItem2;

System.out.println(totalItem2);

Upvotes: 0

Views: 96

Answers (4)

Jay
Jay

Reputation: 2686

Thats because double totalItem2 still holds a double even if you cast the result that you're assigning it to an int

You have to:

int totalItemTemp2 = (int) totalItem2

Upvotes: 2

Elliott Frisch
Elliott Frisch

Reputation: 201409

You can't change the type of totalItem2 at runtime like this,

double totalItem2 = budget2 / costItem2; // <-- totalItem2 is a double, not int
totalItem2 = (int) totalItem2; // <-- truncates

But you could change the declaration to an int with a cast like,

int totalItem2 = (int) (budget2 / costItem2); // <-- truncates

or a long with out,

long totalItem2 = Math.round(budget2 / costItem2); // <-- rounds, no cast!

or an int bu using a float costItem2,

float costItem2 = 32.55f;
int totalItem2 = Math.round(budget2 / costItem2); // <-- rounds, no cast!

Upvotes: 0

Multithreader
Multithreader

Reputation: 878

Your best option is to format the output yourself. Here is how:

NumberFormat numFormat = new DecimalFormat("#.####"); // you can have it as #.## if you only want up to two decimal places
double costItem2 = 32.55;
int budget2 = 713;
double totalItem2 = budget2 / costItem2;

System.out.println(numFormat.format(totalItem2));

so for example, 123.00 would be printed as 123

Upvotes: 1

Aniket Inge
Aniket Inge

Reputation: 25695

casting totalItem2 to int will not change the type of totalItem2(which will still remain a double).

int tmpInt = (int) totalItem2;
System.out.println(tmpInt);

should fix it.

Upvotes: 0

Related Questions