How to Avoid Scientific Notation in Double?

2019-01-07 22:54发布

问题:

Here is my simple code

        @Override
    public void onClick(View v) {
        try {
            double price = Double.parseDouble(ePrice.getText().toString());
            double percent = Double.parseDouble(ePercent.getText().toString());

            double priceValue = price * percent/100.0f;
            double percentValue = price - priceValue;

            moneyToGet.setText(String.valueOf(priceValue));
            moneyToPay.setText(String.valueOf(percentValue));

            moneyToGet.setText("" + priceValue);
            moneyToPay.setText("" + percentValue);

            // catch
        } catch (NumberFormatException ex) {
            // write a message to users
            moneyToGet.setText("");
        }
    }

});

This is a simple code for Percentage Calculator.

What I want is to avoid the Scientific Notation in my Calculator cause I don't want to explain to user what is Scientific Notation.

For example if I want to calculate 100,000,000 and cut 50% of it, it Should give me 50,000,000 which is giving me 5.0E7 And in my case this doesn't make any sense to the user. And of course I know both results are correct. Thanks in Advance.

回答1:

Check answer here. You can write

moneyToGet.setText(String.format("%.0f", priceValue));


回答2:

You can try this DecimalFormat

DecimalFormat decimalFormatter = new DecimalFormat("############");
number.setText(decimalFormatter.format(Double.parseDouble(result)));


回答3:

I would suggest using BigDecimals instead of doubles. That way you will have a more precise control over your calculation precision. Also you can get a non-scientific String using BigDecimal.toPlainString().



回答4:

DecimalFormat decimalFormatter = new DecimalFormat("##.############");
                    decimalFormatter.setMinimumFractionDigits(2);
                    decimalFormatter.setMaximumFractionDigits(15);

This option will help you ##.## suffix 0 before decimal, otherwise output will be .000

 btc.setText(decimalFormatter.format(btcval));

use this for displaying content



回答5:

Use NumberFormater like

NumberFormat myformatter = new DecimalFormat("########");  

String result = myformatter.format(yourValue);