谁能看一下这段代码,告诉我为什么会发生异常?
public static void main(String[] args)
{
int total =100;
int discount_Ammount = 20 ;
int newAccount=Integer.parseInt( String.valueOf(Math.floor(total - discount_Ammount)).trim());
}
方法floor返回双精度值,然后我将其转换为整数,所以我将其转换为字符串,然后转换为整数……有人能帮上忙吗?
发布于 2010-07-01 04:22:43
你不是在“铸造”任何东西。trim()
只删除空格,而空格永远不会出现在String.valueOf(double)
的结果中。
使用造型:
int newAccount = (int) Math.floor(total - discount_Ammount);
Java是一种强类型编程语言,而不是脚本语言。不支持字符串和其他类型之间的隐式转换。
或者,完全取消floor()
操作,因为您已经在处理int
数量,而floor()
没有意义:
int newAccount = total - discount_Ammount;
如果您使用的是货币,请使用BigDecimal
类,以便可以使用会计系统所需的舍入规则。在使用double
时,您无法控制这一点。
发布于 2010-07-01 04:22:44
你试过这个吗?
int newAccount = (int) Math.floor(total - discount_Ammount);
甚至是这个!
int newAccount = total - discount_Ammount;
发布于 2010-07-01 04:22:31
不需要执行Integer.parseInt( String.valueOf(
要强制转换为int,只需执行(Int)(诸如此类)
So int newAccount=(int)(Math.floor(total - discount_Ammount));
https://stackoverflow.com/questions/3153079
复制相似问题