Java Round up a Float value to an Int value
This tutorial shows you how to round up a float value to an int value using ceil() and floor() methods.
Round up float value to an int value using ceil()
The below example shows you how to return smallest float value that is greater than or equal to argument (the float value) as an int value.
package com.sneppets.example; public class RoundUpExample1 { public static void main (String[] args) { int workHours = 8; int unavailablePercentage = 40; float availabilityIndex = (float)(100 - unavailablePercentage)/100 * workHours; System.out.println("Availability Index float value: " + availabilityIndex); int roundUpAvailabilityIndex = (int) (Math.ceil(availabilityIndex)); System.out.println("Round Up Availability Index value using Math.ceil(): " + roundUpAvailabilityIndex); } }
Output
Availability Index float value: 4.8 Round Up Availability Index value using Math.ceil(): 5
Round up float value to an int value using floor()
The below example shows you how to return largest float value that is lesser than or equal to argument as an int value.
package com.sneppets.example; public class RoundUpExample2 { public static void main (String[] args) { int workHours = 8; int unavailablePercentage = 40; float availabilityIndex = (float)(100 - unavailablePercentage)/100 * workHours; System.out.println("Availability Index float value: " + availabilityIndex); int roundUpAvailabilityIndex = (int) (Math.floor(availabilityIndex)); System.out.println("Round Up Availability Index value using Math.floor(): " + roundUpAvailabilityIndex); } }
Output
Availability Index float value: 4.8 Round Up Availability Index value using Math.floor(): 4
Further Reading
- Convert comma separated String to List
- How to find intersection of two Sets
- Get time units hours and minutes from Date in String format
- Compare two Sets and check its Equality efficiently