繁体   English   中英

在 Java 中的十进制格式后删除 E0(指数形式)

[英]removing E0 (exponent form) after Decimal Formatting in Java

import java.math.RoundingMode;

public class DecimalFormat
{
    public static void main(String[] args)
    {
    java.text.DecimalFormat df = new java.text.DecimalFormat("#.######E0");
    df.setRoundingMode(RoundingMode.CEILING);

    System.out.println(df.format(3));
    System.out.println(df.format(19.346346436));
    }
}

output 是:

3E0
1.934635E1

有什么方法可以在不更改 1.934635E1 的情况下将 3E0 更改为 3?

您可以在格式化之前检查 Integer,如下所示:

让我们假设 y 是我们包含数值的变量

      double y=25.33;
      java.text.DecimalFormat df = new java.text.DecimalFormat("#.######E0");
      df.setRoundingMode(RoundingMode.CEILING);
      System.out.println(y == (int)y ? (int)y: df.format(y));

您也可以将 integer 值放入变量 y 以获得所需的 output。 我希望这会有所帮助。

我会编写一个自定义格式,以不同的方式处理long输入和double输入。 像这样的东西(不打算作为一个完整的自定义格式,只是一个演示):

public class SO_73377546 {

    public static void main(String[] args) {
        NumberFormat df = new CustomFormat("#.######E0", RoundingMode.CEILING);

        System.out.println(df.format(3));
        System.out.println(df.format(19.346346436));
    }

}

class CustomFormat extends NumberFormat {

    private DecimalFormat standardFormat;
    private DecimalFormat scientificFormat;

    public CustomFormat(String pattern, RoundingMode roundingMode) {
        this.standardFormat = new DecimalFormat("#");
        this.scientificFormat = new DecimalFormat(pattern);
        scientificFormat.setRoundingMode(roundingMode);
    }

    @Override
    public StringBuffer format(double number, StringBuffer toAppendTo, FieldPosition pos) {
        return scientificFormat.format(number, toAppendTo, pos);
    }

    @Override
    public StringBuffer format(long number, StringBuffer toAppendTo, FieldPosition pos) {
        return standardFormat.format(number, toAppendTo, pos);
    }

    @Override
    public Number parse(String source, ParsePosition parsePosition) {
        // TODO: Untested
        return scientificFormat.parse(source, parsePosition);
    }
}

运行时,将生成以下 output:

3
1.934635E1

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM