我试图将双精度转换成int但我没有得到预期的结果。有人能帮我吗? 这是我的代码。我的预期输出是21,但我一直得到21.0。
double costItem2 = 32.55;
int budget2 = 713;
double totalItem2 = budget2 / costItem2;
totalItem2 = (int) totalItem2;
System.out.println(totalItem2);
答案 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);
应该修复它。