JavaRush/Java Blog/Random EN/Rounding numbers in Java

Rounding numbers in Java

Published in the Random EN group
members
Floating point numbers (float, double) are used when calculating expressions that require decimal precision. High accuracy is often needed in accounting and other computing operations. Rounding numbers in Java - 1But do we always need a long “tail” of numbers after the decimal point? Maybe an accuracy of three real parts is enough for us? And we are satisfied with this option, how to properly perform rounding? This is exactly what we will talk about today: we will look at ways to round numbers in Java .

String format

As a first method, we'll look at rounding double:
double value = 34.766674;
String result = String.format("%.3f",value);
System.out.print(result);//  34,767
As a result, we will format our floating point number 34766674 with a precision of 3 decimal places , since in the formatting instructions we specified three decimal places "%.3f. In turn, %f when formatting a string indicates the type of floating point numbers, which includes the data type double and float in Java. In the example above, we output the resulting value to the console. Now the question is: how could we shorten this? It’s simple: you need to use printf, which in turn is format + print. As a result, the previous Our example would be reduced to:
double value = 34.766674;
System.out.printf("%.3f",value);
In addition to this method , the out instance of the PrintStream class also has a format method, which works similarly:
double value = 34.766674;
System.out.format("%.3f",value);
Rounding occurs in the HALF_UP mode - towards the number that is closer to the one being cut off (to 0 or 10). If these numbers are equidistant (in the case of 5), then rounding is performed up. Example:
String firstResult = String.format("%.3f",7.0004);// 7,000
String secondResult = String.format("%.3f",7.0005);// 7,001
String thirdResult = String.format("%.3f",7.0006);// 7,001
We will discuss rounding modes in more detail below. Rounding numbers in Java - 2

DecimalFormat

Another option is to use the DecimalFormat class . It is designed to format any number in Java, be it an integer or a floating point number. When we instantiate DecimalFormat, we can pass it a format string. It will indicate how many decimal places to format for the input. This is what our example would look like using DecimalFormat :
double value = 34.766674;
DecimalFormat decimalFormat = new DecimalFormat( "#.###" );
String result = decimalFormat.format(value);
System.out.print(result);//34,767
The line #.### is a pattern that indicates that we are formatting the passed value to 3 decimal places. To change the pattern after the DecimalFormat object has been created, you can use its applyPattern and applyLocalizedPattern methods :
DecimalFormat decimalFormat = new DecimalFormat("#.###");
decimalFormat.applyPattern("#.#");
decimalFormat.applyLocalizedPattern("#.#####");
But today we are talking about rounding, aren’t we? When truncating a number with decimal places beyond the specified pattern, DecimalFormat rounds the number up if the last truncated number is greater than 5. But what if the number is 5? It turns out that it is exactly in the middle between the nearest integers. What then? In this case, the previous number is taken into account. If it is even, rounding is done:
DecimalFormat decimalFormat = new DecimalFormat("#.###");
String result = decimalFormat.format(7.4565);
System.out.println((result));// 7,457
If odd, it is not performed:
DecimalFormat decimalFormat = new DecimalFormat("#.###");
String result = decimalFormat.format(7.4575);
System.out.println((result));// 7,457
There is a slight difference between formatting floating point numbers using String.format() and DecimalFormat.format(). The first one will always print trailing zeros even if there is no fractional part. Eg:
String firstResult = String.format("%.3f", 7.000132);
System.out.println((firstResult)); // 7.000

DecimalFormat decimalFormat = new DecimalFormat("#.###");
String secondResult = decimalFormat.format(7.000132);
System.out.println((secondResult));  // 7
As we can see, when formatting the number 7.000132 to three decimal places, String's format() method will output 7.000, while DecimalFormat's format() method will output 7. That is, you can choose String.format() or DecimalFormat. format() depending on whether you need trailing zeros or not. Using the methods described above, we received the result in the form of a string. Let's look at ways to get back exactly the numeric values.

Math

It is impossible not to mention a special class tailored for various arithmetic operations with numbers - Math . Rounding numbers in Java - 3This class also has methods for rounding, but unlike those already described, they do not allow you to set a certain number of decimal places, but rather round to an integer:
  • Math.ceil() rounds up to the nearest integer, but returns not an integer type, but a double:

    double value = 34.777774;
    double result = Math.ceil(value);
    System.out.println((result)); //35.0

    Even if we have 34.0000000, after using Math.ceil we will still get 35.0.

    Math.floor() rounds down to the nearest integer, also returning the result as double:

    double value = 34.777774;
    double result = Math.floor(value);
    System.out.println((result)); //34.0

    Again, even if we have a value of 34.999999999, then after using Math.floor we will get 34.0.

  • Math.round () - rounds to the nearest integer, giving the result int:

    double value = 34.777774;
    int result = Math.round(value);
    System.out.println((result)); //35

    If our number is 34.5, it is rounded to 35, but if it is slightly less than 34.499, the number is truncated to 34.

    In order not to simply cut off the entire real part, but to regulate this process to a certain number of decimal places and at the same time round, the number is multiplied by 10^n (10 to the power of n), where n is equal to the number of necessary decimal places. After this, they use some method of the Math class to round, and then divide by 10^n again:

    double value = 34.777774;
    double scale = Math.pow(10, 3);
    double result = Math.ceil(value * scale) / scale;
    System.out.println((result)); //34.778

    Math.pow - takes two arguments. The first is the number, the second is the power to which it needs to be raised.

Rounding with BigDecimal

BigDecimal is a class that allows you to work with floating point numbers. In particular, its main feature is that it can store fractional numbers of arbitrary length (that is, there is no limit on the range of the number). In addition, this class stores various methods for arithmetic processing, including rounding. The class of this object can be created by setting the constructor to double, string to display a floating point number, double and MathContext , and so on. MathContext is a combination of the RoundingMode and a number that describes the total number of digits in the searched value. Rounding rules RoundingMode: DOWN - rounding towards zero. UP —rounding from zero mode. CEILING - rounding towards positive infinity. FLOOR - rounding towards negative infinity. HALF_UP - Rounds to the "nearest neighbor" if both neighbors are not equidistant (that is, when the number being rounded is 5). In this case, rounding up is performed. HALF_DOWN - rounding towards the “nearest neighbor”. If both neighbors are not equidistant, in this case round down. HALF_EVEN - Rounds to the "nearest neighbor" if both neighbors are not equidistant. In this case, round to the even neighbor (as in DecimalFormat described above). UNNECESSARY - Used to confirm that the requested operation has the correct result. Therefore, rounding is not required. Example:
MathContext context = new MathContext(5, RoundingMode.HALF_UP);
double value = 34.777554;
BigDecimal result = new BigDecimal(value, context);
System.out.println(result); //34.778
In addition to the ability to set a rounding rule in the constructor, BigDecimal allows you to set the rounding mode after the instance is created. To do this, use the setScale method , in which you need to set the number of decimal places and rounding rules:
double value = 34.777554;
BigDecimal result = new BigDecimal(value);
result = result.setScale(3, RoundingMode.DOWN);
System.out.println(result); //34.777
BigDecimal also has internal int variables designed to set the rounding mode ( ROUND_DOWN , ROUND_CEILING , ROUND_FLOOR ...) These are rounding rules similar to those presented in the RoundingMode class and are similarly used in setScale :
BigDecimal result = new BigDecimal(value);
result = result.setScale(3, BigDecimal.ROUND_DOWN);
Read more about the BigDecimal class in this article .
Comments
  • Popular
  • New
  • Old
You must be signed in to leave a comment
This page doesn't have any comments yet