简体   繁体   中英

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 is:

3E0
1.934635E1

Is there any way where i can change 3E0 to just 3 without changing 1.934635E1?

You can check for Integer before formatting like below:

lets assume y is our variable containing numerical value

      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));

You can put integer value as well in variable y to get the desired output. I hope this help.

I would write a custom format that handles long and double inputs differently. Something like this (not intended as a complete custom format, just a demonstration):

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);
    }
}

When run, this produces the following output:

3
1.934635E1

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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