How to round a floating-point number to an integer in Java

2 Answers

0 votes
public class RoundFloatingPoint {
    public static void main(String[] args) {
        float x = 9382.4f;
        long y = Math.round(x);
        System.out.println(y);
        
        x = 9382.5f;
        y = Math.round(x);
        System.out.println(y);
    }
}



/*
run:

9382
9383

*/

 



answered May 14, 2025 by avibootz
0 votes
import java.text.NumberFormat;
import java.math.RoundingMode;

public class RoundFloatingPoint {
    public static void main(String[] args) {
        // large numbers include commas for readability (e.g., "9,382"). 
        // When you try to parse this formatted string into an integer using Integer.parseInt(), 
        // it fails because "9,382" is not a valid integer representation 
        // (commas are not allowed in number parsing).
        
        // Define floating-point value to round
        double x = 938.4;

        // Initialize NumberFormat instance
        NumberFormat f = NumberFormat.getNumberInstance();
        f.setRoundingMode(RoundingMode.HALF_UP);
        f.setMaximumFractionDigits(0);

        // Format the rounded number correctly
        String roundedStr = f.format(x);
        int y = Integer.parseInt(roundedStr); // Convert formatted string to integer
        System.out.println("Rounded value: " + y);
        
        x = 938.5;
        // Format the rounded number correctly
        roundedStr = f.format(x);
        y = Integer.parseInt(roundedStr); // Convert formatted string to integer
        System.out.println("Rounded value: " + y);
        
    }
}



/*
run:

Rounded value: 938
Rounded value: 939

*/

 



answered May 14, 2025 by avibootz
edited May 14, 2025 by avibootz
...