Search code examples
javadecimalformatexponent

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?


Solution

  • 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.