Search code examples
javastringformattingdoublebigdecimal

Formatting A Double In A String Without Scientific Notation


I have a double. double foo = 123456789.1234;. I want to turn foo into a String. String str = foo+"";. But now foo is equal to "1.234567891234E8". Is there a way I can turn foo into a String without scientific notation? I've tried

String str = String.format("%.0f", foo);

But that just removes the decimals. It sets str to "123456789"; I've tried

String str = (new BigDecimal(foo))+"";

But that loses accuracy. Its sets str to "123456789.1234000027179718017578125";


Solution

  • Use just %f instead of %.0f.

    import java.math.BigDecimal;
    
    public class Main {
        public static void main(String[] args) {
            double foo = 123456789.1234;
            String str = String.format("%f", foo);
            System.out.println(str);
    
            // If you want to get rid of the trailing zeros
            str = new BigDecimal(str).stripTrailingZeros().toString();
            System.out.println(str);
        }
    }
    

    Output:

    123456789.123400
    123456789.1234