1

Should be simple I know but I cant find an answer anywhere. I'm trying to round up to two decimal places, so if my answer is 164.9835 I'd like the answer to be displayed as 164.99. But what I have so far is rounding it to 164.98 for some reason.

Any help much appreciated.

            double number1 = Double.parseDouble(num1.getText().toString());
            double number2 = Double.parseDouble(num2.getText().toString());
            double number3 = Double.parseDouble(num3.getText().toString());
            double number4 = Double.parseDouble(num4.getText().toString());
            double sum = (((number1 * number2)/1000)*0.5)*(number3 - number4);
            total.setText (String.format("£%s", new java.text.DecimalFormat("##.##").format(sum)));
3
  • Why would that round to 164.99?
    – codeMagic
    Commented Aug 28, 2018 at 22:21
  • Typical approaches to rounding would say that 164.9835 rounds down to 164.98, not up to 164.99. Are you sure that you want 164.980000000000000001 to become 164.99? Commented Aug 28, 2018 at 22:21
  • Yeah I'm afraid i do need it to round up, even at 164.980000000001, it needs to be 164.99. It's to provide a bit of a legal safety net I suppose for what I'm doing.
    – suxrule
    Commented Aug 28, 2018 at 22:24

1 Answer 1

3

If you want to round up you can use this method

cantDecimal = 2; number = 164.9835

public static double aroundUp(double number, int canDecimal) {
    int cifras = (int) Math.pow(10, canDecimal);
    return Math.ceil(number * cifras) / cifras;
}

return = 164.99

Extra: Ceil Method in Math. The method ceil gives the smallest integer that is greater than or equal to the argument.

3
  • Mathematically, this works, but I worry about the imprecision of floating-point math breaking your algorithm in some places. I would consider skipping the division and hacking in the decimal separator using string manipulation. Commented Aug 28, 2018 at 22:38
  • Thanks, but a proper noob question now...Where does this go/how do I apply this to my code above? Thanks
    – suxrule
    Commented Aug 28, 2018 at 22:41
  • you need copy this method and call: total.setText (String.format("£%s", aroundUp(sum,2))); do not forget to vote the answer :) Commented Aug 28, 2018 at 22:52

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.