What is math round in java

Round off in Java

Java Course - Mastering the Fundamentals

Round off is a term in mathematics that refers to the conversion of a decimal value to the nearest integer value.

Math.round() is one of the many built-in Java methods that allows you to round a floating-point number to the nearest whole number.

  • It takes a single argument of type double or float .
  • It returns the rounded value as a long or an int , respectively.
  • If the fractional part of the number is less than 0.5, it rounds down. If it’s 0.5 or greater, it rounds up.

Introduction to Math.round() in java

Round off is used to convert decimal values to integer values for ease of calculations or according to the need of calculation. Values are rounded off to their nearest integer. These values can either be rounded off to a higher integer or a lower integer. If the decimal value is greater than 0.5 then the decimal value will be rounded off to its higher value and if the decimal value is less than 0.5 then it will be rounded off to its lower value.

Lets’s see some simple examples to see how we round off normally in mathematics:

2 . 7 6 8 8 6 7 8 2.7688678 2 . 7 6 8 8 6 7 8 = 3 3 3

− 1 . 2 3 4 7 7 -1.23477 − 1 . 2 3 4 7 7 = − 1 -1 − 1

Primitive data types are data types that are not considered objects and represent variables. Most of the variables we declare are of primitive data types in java.

Читайте также:  Python комментарии комбинация клавиш

There are 8 primitive data types in Java: int , byte , short , long , float , double , boolean , and char . In this article, we will focus on two primitives: float and double .

Both float and double are floating-point types that store fractional numbers, i.e., decimal numbers containing one or more decimals.

  • The float data type can store fractional numbers in range 3.4e-038 to 3.4e+038 .
  • The precision of float is only six or seven decimal digits.
  • The double data type can store fractional numbers in the range 1.76-308 to 1.7e+308 .
  • The precision of double is up to 15 digits. Hence, double is preferred when accuracy is needed.

Different ways to Round Off in Java

There are different ways provided by Java libraries to round off floating numbers. Some of these methods are part of the java.lang.Math class. However, there are other approaches that can be used for rounding off in Java without using Math class methods.

Java has a predefined class in its java.lang package known as the Math class, which deals with mathematical calculations. The java.lang.Math class extends the java.lang.Object class, which is a superclass in Java. It contains methods for performing basic numeric operations such as logarithm, square root, trigonometric functions, etc.

different ways to round off in java

1. Using Math.ceil() method

The java.lang.Math.ceil() method is used to find the nearest integer value that is greater than or equal to the number given as an argument.

b. Parameter

The Math.ceil() method takes a double variable as an argument/parameter.

This method returns the nearest floating-point value that is greater than or equal to the number given as an argument to the method.

  • If the argument is Not a Number (NaN), this method will return the argument itself.
  • If the argument is positive or negative Infinity, this method will return Infinity value with the same sign.
  • If the argument is zero, this method will return 0.
  • If the argument is a number less than 0 but greater than -1.0, this method will return -0.
  • If the argument is a positive or negative double value, this method will return the ceiling value, i.e., the nearest value that is greater than or equal to the argument.

Notes: Even though the Math.ceil() method rounds off the argument, the data type of the output will be a double that’s equal to its mathematical integer value. You can remember this by comparing it to the ceiling of your room. A ceiling is at a higher level. The output of the Math.ceil() function will give the upper/greater number as an output.

2. Using Math.floor() method

The java.lang.Math.floor() method is used to find the nearest integer value that is less than or equal to the number given as an argument.

c i e l ( 1 . 2 6 5 6 ) ciel(1.2656) c i e l ( 1 . 2 6 5 6 ) = 1 1 1

c i e l ( 6 8 7 6 . 6 7 7 ) ciel(6876.677) c i e l ( 6 8 7 6 . 6 7 7 ) = 6 8 7 6 6876 6 8 7 6

c i e l ( − 0 . 8 9 7 ) ciel(-0.897) c i e l ( − 0 . 8 9 7 ) = − 1 -1 − 1

b. Parameter The Math.floor() method takes double variable as an argument/parameter.

c. Returns This method returns the nearest floating-point value that is less than or equal to the number given as an argument to the method.

  • If the argument Not a Number(NaN), this method will return argument itself.
  • If the argument is +ve/-ve Infinity, this method will return Infinity with the same sign.
  • If the argument is +ve/-ve Zero, this method will return 0 with the same sign.
  • If the argument is a number less than 0 but greater than -1.0, this method will return -1.
  • If the argument is +ve or -ve double value, this method will return floor value i.e. nearest value that is less than or equal to the argument.

Notes: Even though Math.floor() method rounds off the argument, the datatype of output will be double that’s equal to its mathematical integer value. You can remember this by comparing it to the floor of your room. As the floor is downside/at a lower level, the output of Math.floor() function will give a lower/smaller number as an output.

3. Using Math.round() method

The java.lang.Math.round() method in Java is used to round off decimal numbers to their nearest integer value. This integer value can be either higher or lower than the decimal value being rounded off. This method takes both float and double variables as arguments.

The result of rounding the argument to an integer is calculated by adding 1/2 (i.e., 0.5 ) to the number and then taking the floor of the result. This determines the nearest integer value that is closer to the argument.

Let’s understand it with some examples:

Example 1: Round off 8.76

Example 2: Round off 1.2

b. Parameter The Math.round() method takes floating-point numbers, i.e., both float and double data types, as arguments.

c. Returns This method returns the nearest integer value as an output. It is calculated by adding 1/2 to the argument and then taking the floor of the result.

  • If the argument is Not a Number (NaN), this method will return zero.
  • If the argument is negative infinity or any value less than or equal to the value of Integer.MIN_VALUE , then the function returns Integer.MIN_VALUE .
  • If the argument is positive infinity or any value greater than or equal to the value of Integer.MAX_VALUE , then the function returns Integer.MAX_VALUE .
  • If the argument is a positive or negative number, this method will return the nearest value. The output can be higher or lower than the argument passed, depending on which value is closer.

Notes: This method takes both float and double values as arguments. In the case of float argument, the data type of output is int. In the case of a double argument, the data type of output is long.

Short trick: You can remember this using a short trick. If the decimal value of a positive argument is greater than 0.5 , then it will return the nearest number greater than the argument as the output.

Example: 9.8 will be rounded off to 10 .

If the decimal value of a positive argument is less than 0.5 , then it will return the nearest number smaller than the argument as the output.

Example: 9.2 will be rounded off to 9 .

Note: The above trick is for positive numbers; it will be vice versa for negative numbers.

4. Using format

Apart from using the Math class in Java, there are other ways to round a number. One of those methods is the format() method in Java. This method returns the formatted string in the given format and is one of the easiest ways to format output in Java.

To use this method, we can use the System.out.format() statement for output formatting in Java. Similar to the printf statements in C language, we can specify the format of the output using %c , %f , %d , etc. For example, %f stands for a floating-point number, and we can provide precision for the decimal value using %.4f , which means the output should be a floating-point number rounded to 4 decimal places.

In the Java String format() method, we can specify the format in which the output is expected. Now, let’s see how we can use this method to round off a floating-point number in Java.

In the above program, the format() method is used to print the given floating-point number number to 2 decimal places. The format of the output is specified to the format() method using the format .2f .

In this format, the .2 specifies that we want to display up to 2 decimal places after the dot, and f indicates that we want to print a floating-point number.

5. Using DecimalFormat

DecimalFormat is a subclass of the NumberFormat class in Java. NumberFormat extends the Format class, which is a subclass of the Object class in Java. The hierarchy of the DecimalFormat class can be seen in the provided image.

The java.text.DecimalFormat class is used to format floating-point values according to specific patterns. The format of the expected output is defined using # patterns.

When creating an object of the DecimalFormat class, we specify a pattern using # , which represents the format of the expected output. For example, if the pattern is #.## , it means that the given argument should be rounded off to 2 decimal places. The last decimal place is rounded using the CEILING mode of the RoundingMode class.

Here’s an example program that demonstrates the usage of DecimalFormat:

In the above program, the number num1 is rounded off using the DecimalFormat class. The format of the required output is declared using the # pattern ( #.#### ). This means we want num1 up to 4 decimal places. The rounding mode is set to CEILING , indicating that the last given decimal place should be rounded up.

So, 1087.12345567 rounded to 4 decimal places is 1087.1234 , and the last decimal place ( 4 ) is rounded up using the CEILING mode, resulting in 5 . Hence, the output is 1087.1235 .

Note: We need to import the DecimalFormat and RoundingMode classes in Java using the import statement, as they are not part of the default java.lang package.

Conclusion

  • Round-off is used to convert decimal values into integers.
  • The java.lang.Math class has Math.ceil() , Math.floor() , and Math.round() methods to round off floating-point values.
  • Math.ceil() and Math.floor() explicitly convert the decimal value to higher and lower integer values, respectively. They are used in complex calculations where accuracy is required.
  • Math.round() converts the decimal value to a higher or lower integer value, whichever is nearest.
  • The String format method can be used to round off decimal values up to a desired number of decimal places.
  • The java.text.DecimalFormat class, which is a subclass of java.text.NumberFormat , can be used to format floating-point values into a specific format with the help of RoundingMode .

Источник

Оцените статью