Rafuka
Rafuka

Reputation: 57

Double number formatting in java

I am working on a calculator program in Java and I need to display a number with no more than 15 digits in length (decimal point included).

I've tried to format this number using String.format("%g", myDouble), also with %f, but can't get the result I'm looking for.

The thing is that I need the number:

Also, I do not want any fixed number of digits before or after the decimal point.

Any suggestions?

This is the code snipet where my number gets displayed:

if (("" + myDouble).length() > 15) {
    screen.setText(String.format("%g", myDouble));
} else {
    screen.setText("" + myDouble);
}

One problem is that when the else clause is executed, sometimes the numbers get displayed as 9.0000E7, which is not favorable and is different from the String.format("%g", myDouble) scientific notation which looks more like 9.000e+7.

Upvotes: 0

Views: 1764

Answers (2)

Radiodef
Radiodef

Reputation: 37835

This seems to be close to what you're asking for:

static String format(double n) {
    if(Double.isInfinite(n) || Double.isNaN(n))
        return Double.toString(n);
    String result = BigDecimal.valueOf(n).toPlainString();
    if(result.length() > 15)
        result = String.format("%.15e", n);
    return result;
}

Since your requirement is that the decimal places aren't fixed, I don't really see a way to do it with a formatter exclusively.

If you want a particular number of digits for the scientific notation, then you can use a format like "%.15e" where 15 is the number of decimal digits you want.

Or possibly you want something like:

if(result.length() > 15)
    result = new DecimalFormat("0.###############E0").format(n);

But if you're trying to "block align" to some maximum, then things get complicated because the number of fractional digits depends on the number of digits in the exponent.

Upvotes: 1

Don Scott
Don Scott

Reputation: 3457

Just use the NumberFormat object. See the javadoc for details.

NumberFormat formatter = new DecimalFormat();
if (("" + myDouble).length() > 15) {
    formatter = new DecimalFormat("0.######E0");
    screen.setText(formatter.format(myDouble));
} else {
    formatter = new DecimalFormat("#");
    screen.setText(formatter.format(myDouble));
}

Upvotes: 0

Related Questions