Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to round off value in java

I want to round off the value if the decimal point is above 1. For example,

23/10 = 2.3 -> roundoff to 3
11/10 = 1.1 -> roundoff to 2
15/10 = 1.5 -> roundoff to 2
67/10 = 6.7 -> roundoff to 7
1738/10 = 173.8 -> roundoff to 174

How can I do this in Java, I tried couple of approach but not working as expected.
Please find my sample code below

public class Test {

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

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

}

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

Use the Math library, do not reinvent the wheel.

private int roundUp(float value){
    return (int) Math.ceil(value);
}
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading