0

I want to round up the value. For example,

23.0f / 10.0f = 2.3f -> round up to 3
11.0f / 10.0f = 1.1f -> round up to 2
15.0f / 10.0f = 1.5f -> round up to 2
67.0f / 10.0f = 6.7f -> round up to 7
1738.0f / 10.0 = 173.8f -> round up to 174

My current approach does not work, it rounds to the nearest integer instead of up:

public class Test {

    private static final DecimalFormat df = new DecimalFormat("0.00");

    public static void main(String[] args) {
        final float a = 23;
        final float b = 10;
        final float k = a / b;
        System.out.println(k);
        final float roundup = Math.round(k * 100) / 100;
        System.out.println(roundOff);
    }
}

How can I achieve the desired behavior in Java?

Turing85
  • 18,217
  • 7
  • 33
  • 58
Mike Marsh
  • 387
  • 3
  • 15
  • 4
    Your examples do not match your description. "if the decimal point is above 1" should mean that 1.1 rounds to 1, because the decimal (1) is not above 1. Do you perhaps mean you'd like to round **up** if the decimal is above **zero**? – Ryan M May 08 '22 at 00:35

1 Answers1

2

Use the Math library, do not reinvent the wheel.

private int roundUp(float value){
    return (int) Math.ceil(value);
}
Dropout
  • 13,653
  • 10
  • 56
  • 109