如何将double转换为int

时间:2014-09-12 03:53:24

标签: java int double

我试图将双精度转换成int但我没有得到预期的结果。有人能帮我吗? 这是我的代码。我的预期输出是21,但我一直得到21.0。

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

System.out.println(totalItem2);

4 个答案:

答案 0 :(得分:2)

多数民众赞成因为double totalItem2仍然保持双倍,即使您将结果分配给int

你必须:

int totalItemTemp2 = (int) totalItem2

答案 1 :(得分:1)

您最好的选择是自己格式化输出。方法如下:

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));

因此,例如,123.00将打印为123

答案 2 :(得分:0)

您无法在运行时更改totalItem2的类型,

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

但是您可以使用类似

的演员将声明更改为int
int totalItem2 = (int) (budget2 / costItem2); // <-- truncates

long没有,

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

int使用float costItem2,

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

答案 3 :(得分:0)

totalItem2投射到int不会更改totalItem2的类型(仍然是double)。

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

应该修复它。