任何人都可以查看这段代码并告诉我为什么会发生异常吗?
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());
}
Method floor 返回 double value ,然后我将其转换为整数,所以我将其转换为字符串,然后再转换为整数...拜托,有人可以帮忙吗?
最佳答案
您没有“转换”任何东西。 trim()
仅删除空格,它永远不会出现在 String.valueOf(double)
的结果中。
使用强制转换:
int newAccount = (int) Math.floor(total - discount_Ammount);
Java 是一种强类型编程语言,而不是脚本语言。不支持字符串和其他类型之间的隐式转换。
或者,完全摆脱 floor()
操作,因为您已经在使用 int
数量,并且 floor()
没有意义:
int newAccount = total - discount_Ammount;
如果您正在处理金钱,请使用 BigDecimal
类,以便您可以使用您的会计系统所需的舍入规则。使用 double
时您将无法控制它。
关于java - 整数问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3153079/