首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >格式化数字,使其在没有点的情况下太大时采用科学记数法

格式化数字,使其在没有点的情况下太大时采用科学记数法
EN

Stack Overflow用户
提问于 2016-09-09 01:08:30
回答 2查看 415关注 0票数 0

我有以下问题:我在字符串中存储了很大的值,并且我只能显示7位数长度的数字。这是从字符串转换为浮点型后的例子-我有String300,它应该是300.0,但它是300.0,所有大于7位的东西都应该用科学记数法写(700000000应该是7E+8)它也可以是7.0E8,但我更喜欢7E+8。

我尝试过格式化字符串,但是当我无法在不摆脱科学记数法的情况下摆脱.0时。这有可能吗?

EN

回答 2

Stack Overflow用户

发布于 2016-09-09 01:45:22

java.text包中的类DecimalFormat几乎毫不费力地处理了这一点。针对您的特定案例,稍加一点业务逻辑就可以完成交易。

代码语言:javascript
复制
import java.text.DecimalFormat;
import java.text.NumberFormat;

public class NumberFormatter
{
  public static void main(String args[])
  {
    String stringInput = "1234.5678";
    String outputString = null;
    if (stringInput.length() < 8)
    {
      outputString = stringInput;
    }
    else
    {
      outputString = scientificOutput(stringInput);
    }
    System.out.println(outputString);
  }

  private String scientificOutput(String input)
  {
    NumberFormat formatter = new DecimalFormat("0.###E0");
    Double d = Double.parseDouble(input);
    if (d % 1 == 0)
    {
      // is int
      return formatter.format(d.intValue());
    }
    else
    {
      // is a double
      return formatter.format(d); 
    }
  }
}
票数 0
EN

Stack Overflow用户

发布于 2016-09-09 03:13:51

试试这个:

代码语言:javascript
复制
String inputValue = "700000000";
String result;

DecimalFormat df1 = new DecimalFormat("@######");
df1.setMinimumFractionDigits(0);
DecimalFormat df2 = new DecimalFormat("@#####E0");
df2.setMinimumFractionDigits(1);

if (inputValue.length() <= 7) {
    result = df1.format(Double.parseDouble(inputValue));
} else {
    result = df2.format(Double.parseDouble(inputValue));
}
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/39396680

复制
相关文章

相似问题

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