Mohamed Hemdan
Mohamed Hemdan

Reputation: 303

Formatting a Double variable

I'm facing a problem with formatting a double variable showing to users. The variable should be a double but after some calculations init, it shows to users including the E sign. How can i remove the E sign from it and only shows it it's normal behavior?

Thanks!

double formattedNumber = Double.parseDouble(new DecimalFormat("#############").format(myNum * calcal));

Upvotes: 0

Views: 78

Answers (1)

Dennis Hendriks
Dennis Hendriks

Reputation: 86

There are various ways to convert double values to a textual representation. The easiest way is to use string formatting. Consider the following unit test:

@Test
public void test() {
    System.out.format("%s%n", 1.12345e37);

    System.out.format("%e%n", 1.12345e37);
    System.out.format("%f%n", 1.12345e37);
    System.out.format("%g%n", 1.12345e37);

    System.out.format("%E%n", 1.12345e37);
    System.out.format("%G%n", 1.12345e37);
}

When executed it prints the following:

1.12345E37
1.123450e+37
11234500000000000000000000000000000000.000000
1.12345e+37
1.123450E+37
1.12345E+37

As you can see, the various format patterns give different results. The %f variant gives what I assume is the answer you desire. See String.format and Format String Syntax for more information.

Upvotes: 2

Related Questions