首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >整数的问题

整数的问题
EN

Stack Overflow用户
提问于 2010-07-01 04:18:59
回答 3查看 227关注 0票数 1

谁能看一下这段代码,告诉我为什么会发生异常?

代码语言:javascript
运行
复制
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返回双精度值,然后我将其转换为整数,所以我将其转换为字符串,然后转换为整数……有人能帮上忙吗?

EN

回答 3

Stack Overflow用户

发布于 2010-07-01 04:22:43

你不是在“铸造”任何东西。trim()只删除空格,而空格永远不会出现在String.valueOf(double)的结果中。

使用造型:

代码语言:javascript
运行
复制
int newAccount = (int) Math.floor(total - discount_Ammount);

Java是一种强类型编程语言,而不是脚本语言。不支持字符串和其他类型之间的隐式转换。

或者,完全取消floor()操作,因为您已经在处理int数量,而floor()没有意义:

代码语言:javascript
运行
复制
int newAccount = total - discount_Ammount;

如果您使用的是货币,请使用BigDecimal类,以便可以使用会计系统所需的舍入规则。在使用double时,您无法控制这一点。

票数 14
EN

Stack Overflow用户

发布于 2010-07-01 04:22:44

你试过这个吗?

代码语言:javascript
运行
复制
int newAccount = (int) Math.floor(total - discount_Ammount);

甚至是这个!

代码语言:javascript
运行
复制
int newAccount = total - discount_Ammount;
票数 8
EN

Stack Overflow用户

发布于 2010-07-01 04:22:31

不需要执行Integer.parseInt( String.valueOf(

要强制转换为int,只需执行(Int)(诸如此类)

代码语言:javascript
运行
复制
So int newAccount=(int)(Math.floor(total - discount_Ammount));
票数 3
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/3153079

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档