0

I am making an app, and I used decimal format to round numbers. It worked fine till 5-6 digits but only rounds to 2 decimals.

I made some edits but it didn't work.Till 5-6 digits,It rounds perfectly, i.e. leaving only 3 decimal places after rounding,but when I go over 7-8,It just rounds two decimal places

This is my code

   double result = Double.parseDouble(myEditText.getText().toString());
        String i = Double.toString(result);
        int int1 = i.indexOf(".");
        String io = "0.";
        int ii = (i.length() - int1 - 1)-3;
        for (int iio = 0;iio <= ii;iio++){

            io = io+"#";
        }



        DecimalFormat decimalFormat = new DecimalFormat(io);
        String string = decimalFormat.format(result);
        result = Double.parseDouble(string);
        textArea.setText(textArea.getText().toString() + " = "+result);


For eg. I input 1.678394762 It gives me 1.6783948, While it should give 1.678 If I input 1.45678,It gives me expected 1.457

  • It's very unclear what your trying to do here. You parse a string to a number, turn it back to a string to build a format, print the number using that format, parse it again and then convert it back to a string. Why? – Andy Turner Jun 01 '19 at 19:10
  • The last line is actually to convert it to words, I accidently added it there.I will remove it right away – Demon App Programmer Jun 02 '19 at 06:49
  • It is working as per the logic you have defined. If you want to round it off to just 3 decimal places after the decimal point, you can just hardcode the digits to round off to like `DecimalFormat decimalFormat = new DecimalFormat("0.###"); String string = decimalFormat.format(result);` – raxerz Jun 02 '19 at 07:42
  • ok....I thought that the amount of decimal places is the number of decimals to be rounded,Thank You – Demon App Programmer Jun 02 '19 at 08:01

0 Answers0