首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >10位android

10位android
EN

Stack Overflow用户
提问于 2011-04-21 02:18:29
回答 2查看 433关注 0票数 0

我正在写一个Android计算器,并希望限制输出的字符数量为10例如:

1: ans = 1.23456789101

应显示1.23456789

2: ans = 1234.56789101

应显示1234.56789

3: ans = 123456789101

应显示1234567890

这是我到目前为止所拥有的,但它只适用于1个数字之前“。

代码语言:javascript
运行
复制
        ans = (double)Math.round(ans * 100000000) / 100000000;
        String output = String.valueOf(ans);
        if(output.endsWith(".0")){
            output=output.substring(0, output.length()-2);
        }
        textbox.setText(output);

我该怎么做呢?

EN

回答 2

Stack Overflow用户

回答已采纳

发布于 2011-04-21 02:39:08

您可以使用一系列关于该值的if语句并结合DecimalFormat来完成此操作

代码语言:javascript
运行
复制
if (value >= 10 && value < 100) DecimalFormat formatter = new DecimalFormat("#.#########");
else if (value >= 100 && value < 1000)) DecimalFormat formatter = new DecimalFormat("#.########");
else if (value >= 1000 && value < 10000)) DecimalFormat formatter = new DecimalFormat("#.#######");

etc etc

textBox.setText(String.valueOf(formatter.format(value));

我相信有一种更优雅的方式来处理这件事,但这至少是可行的。对于超过10位的值,您还可以在else if中的链中包含一些截断代码。

票数 1
EN

Stack Overflow用户

发布于 2011-04-21 02:23:34

我建议使用DecimalFormat类。它将允许您自定义您的值的显示。我的好先生,不要因为做小数点后的减法而伤害到yousefl。此外,请仔细阅读舍入行为,以确保它将执行您想要的操作(您为DecimalFormat提供了一个未舍入的值)。

代码语言:javascript
运行
复制
double d = 1234.543534535345345345;
DecimalFormat twoDForm = new DecimalFormat("#.##"); // round to 2 decimals
System.Out.Printline(Double.valueOf(twoDForm.format(d));
票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/5734816

复制
相关文章

相似问题

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