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
*/