Roman
Roman

Reputation: 1019

Howto format number with DecimalFormat with optional scientific notation

I am using a pattern "#0.00##" to format numbers, it works as expected for most input. But sometimes sources number are smaller ie: 6.84378E-05, and gets converted into "0,0001".

Is it possible to format only such numbers (not fitting standard pattern) using scientific notation? leaving all "normal" numbers intact? with single pattern.

I have to use only a single DecimalFormat pattern, without any extra code.

EDIT: To better explain why I need single DecimalFormat : I am using an external library and can only define a pattern to configure output.

Upvotes: 3

Views: 1596

Answers (1)

Italo Borssatto
Italo Borssatto

Reputation: 15689

You can have distinct patterns only for positive and negative values.You should do something like:

public class DecimalScientificFormat extends DecimalFormat {
    private static DecimalFormat df = new DecimalFormat("#0.00##");
    private static DecimalFormat sf = new DecimalFormat("0.###E0");

    @Override
    public StringBuffer format(double number, StringBuffer result, FieldPosition fieldPosition) {
        String decimalFormat = df.format(number);
        return (0.0001 != number && df.format(0.0001).equals(decimalFormat)) ? sf.format(number, result, fieldPosition) : result.append(decimalFormat);
    }
}

Upvotes: 2

Related Questions