Write a Java program to round a float number to specified decimals


This Java program takes a floating-point number (x) and rounds it to a specific number of decimal places (decimal_place) using the BigDecimal class. The result is printed to the console.

The BigDecimal class is used because it provides precise decimal arithmetic and can handle numbers with many digits. The ROUND_HALF_UP rounding mode is used, which rounds up if the next digit is 5 or higher, and rounds down otherwise.

The program first converts the floating-point number x to a BigDecimal using its string representation, and then calls the setScale method to set the number of decimal places to be rounded to. The result is assigned to the variable num.

Finally, the original number x and the rounded number num are printed to the console using System.out.printf and System.out.println, respectively.

Note that in the printf statement, the format string %.7f is used to print the original number x with 7 decimal places. This is not necessary for the rounding operation, but is included to illustrate the difference between the original number and the rounded number.

Source Code

import java.lang.*;
import java.math.BigDecimal;
public class Round_FloatNumber
{
	public static void main(String[] args)
	{
		float x = 84.2573212f;
		BigDecimal result;
		int decimal_place = 2;
		BigDecimal num = new BigDecimal(Float.toString(x));
		num = num.setScale(decimal_place, BigDecimal.ROUND_HALF_UP); 
		System.out.printf("Given number: %.7f\n",x);
		System.out.println("Rounded upto 2 decimal: "+num);
	}
}

Output

Given number: 84.2573242
Rounded upto 2 decimal: 84.26

Example Programs