Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

like image 814
Coding Mason Avatar asked Aug 14 '26 09:08

Coding Mason


1 Answers

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
like image 154
Arvind Kumar Avinash Avatar answered Aug 16 '26 21:08

Arvind Kumar Avinash



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!