Search code examples
javaroundingprecisionbigdecimal

How to round up the result without losing its precision in android


I am building a basic calculator functionality in android. But I am facing little problem with rounding up the numbers when the result is get displayed in the TextView.

I am doing multiplication of 123456789 * 123456789 and getting result which I am not able to accommodate in my TextView. Also the Actual result of above operation is 1.5241E16 when performed in Android's in built Calculator. Can anyone tell me that how can I achieve this result in my calculator app? Below is little snippet about what I am trying to do:

public static double round(double unrounded, int precision, int roundingMode)
    {
        BigDecimal bd = new BigDecimal(unrounded);
        BigDecimal rounded = bd.setScale(precision, roundingMode);
        return rounded.doubleValue();
    }

    num = num * Double.parseDouble(txtCalc.getText().toString());
    num = round(num, 3, BigDecimal.ROUND_HALF_UP); //where 3 is the precision of number

Plz Help me to achieve the result 1.5241E16 for 1...9 * 1....9


Solution

  • The scientific notation does lose accuracy. 1.5241E16 simply means the answer is roughly 1.5241*10,000,000,000,000,000 meaning if you can decide how many decimal places you want to display, you can just divide you number by 10^X and concatenate the result.

    So if my resulting number was 1234567890 and I wanted to display this to 3 decimal places. I would do 1234567890 / 10^9 (because there are 9 digits after the first digit) and then I would simply cancatenate everything after char 5 (1 place for the whole number, 1 place for the dot and then 3 decimal places). If you want to round the last decimal place, simply check if the number at position 6 is greater than or eqaul to 5 and just increment the last number by 1.

    Here this gives the result you desire.

    double num1 = 123456789L;
    double num2 = 123456789L;
    String result = num1*num2+"";
    if(result.contains("E")){ //if result is in scientific notation
        //take the first 6 characters only and part containing the E, drop everything else.
        result = result.substring(0, 6) + result.substring(result.indexOf("E"));
    }
    System.out.println("Result is = " + result);
    

    The output from my Groovy shell:

    Result is = 1.5241E16