Easy ways to round doubles in java to two decimal places

Rounding doubles in Java to two decimal places is often required when dealing with financial data or other types of data that require a high level of precision. The double data type in Java will represent 15 letters when used before a variable, the figure following the decimal point. However, there are situations when representing rupees and other units simply call for two decimal places after the decimal point. The Apache Common library, Math.round(), BigDecimal using the setScale() method, and other tools may all round a double number to two decimal places. Commonly used by programmers “round()” method to round two decimal places to discover approximate decimal values. In addition, how to round doubles in Java numbers in Java to make calculations more convenient.

Round doubles in Java to two decimal places

Rounding doubles in Java to two decimal places is often required when dealing with financial data or other types of data that require a high level of precision.

For example, when calculating the price of an item with taxes or discounts, the final result may include many decimal places. However, for display purposes, it’s often desirable to round the final price to two decimal places, as that is the convention for representing currency values.

Rounding doubles to two decimal places can also be helpful when performing comparisons between values. Since doubles are stored with limited precision in memory, performing comparisons between two double values that are expected to be equal may return unexpected results due to rounding errors. Rounding the values to two decimal places can help mitigate this issue.

Furthermore, rounding doubles to two decimal places can help reduce the amount of data that needs to be stored or transmitted. Storing or transmitting values with many decimal places can take up more space or bandwidth than necessary, so rounding the values to two decimal places can help save resources.

Overall, rounding doubles in Java to two decimal places can be useful for improving readability, reducing errors, and saving resources when working with financial or other types of data that require high precision.

How to round doubles in java

Method 1:  Use Math.round() Method to round a double to two decimal places

The static function “Math.round()” is a part of the Math class. It rounds the decimal points to the closest whole number. The Math.round() function takes “(Doublevalue*100.0)/100.0” as an input to round numbers up to two decimal places.

Use the Math.round() function to round the number up to two decimal places by using the syntax shown below:

Math.round(Doublevalue*100.0)/100.0

Example: Firstly, we’ll make a variable of type double called “dbl” and initialize it with the following value:

double dbl = 5211.1246;
System.out.println("Original Double value: "+dbl);

To round off the double value, we will use the “Math.round()” function; and then print the updated value using the “System.out.println()” method:

double roundVal = Math.round(dbl*100.0)/100.0;
System.out.println("Updated rounded Double value: "+roundVal);

The complete sample program is available here for you to compile and run:

public class Example {

        public static void main(String[] args) {
                double dbl = 5211.1246;
                System.out.println("Original Double value: "+dbl);
                double roundVal = Math.round(dbl*100.0)/100.0;
                System.out.println("Updated rounded Double value is: "+roundVal);
        }
}

As a result, the double number was correctly rounded to two decimal places:

linuxhint@DESKTOP-XXXXXX:~$ java Example
Original Double value: 5211.1246
Updated rounded Double value is: 5211.12

Method 2: Use the BigDecimal class to round a double to two decimal places.

Using the BigDecimal class “setScale()” function, we can additionally round double numbers. The “java.math.BigDecimal” package contains this class.

Syntax:

BigDecimal(dbl).setScale(number, RoundingMode.HALF_UP);

The BigDecimal class object “dbl” in this case will be invoked by the “setScale()” function. The two arguments that this method accepts are “number” and “Rounding Mode” where the number is an integer value that refers to the scale to round the decimal value and the RoundingMode represents the mode of rounding the decimal value.

import java.util.*;
import java.lang.*;
import java.io.*;
import java.math.BigDecimal;
import java.math.RoundingMode;

public class Main 
{
  public static void main(String[] args)
  {
      double val1 = 4312.186462;
      System.out.println("Double value: "+val1);
    
      BigDecimal bd = new BigDecimal(val1).setScale(2, RoundingMode.HALF_UP);
      double val2 = bd.doubleValue();
      System.out.println("Rounded Double value: "+val2);
  }
}

Output:

Double value: 4312.186462
Rounded Double value: 4312.19

Method 3: How to round doubles in Java using DecimalFormat

The class “DecimalFormat” is used to format decimal numbers. This class provides a formatting Pattern to format double to 2 decimal places. It belongs to the NumberFormat class as a subclass.

Syntax:

DecimalFormat("###.##");

Here, “###.##” represents the format for rounding the number to two decimal places.

For Example:

DecimalFormat dcf = new DecimalFormat("###.##");

Call the “format()” function, with the double value “dbl” as an argument, to print the rounded value:

System.out.println("Updated rounded Double value: "+dcf.format(dbl));

The output displays the rounded double value up to two decimal places:

linuxhint@DESKTOP-XXXXXX:~$ java Example
Original Double value: 5213.1246
Updated rounded Double value is: 5213.12

Method 4: How to round doubles in Java by Utilizing NumberFormat Class

The “NumberFormat” is the class that belongs to the java.text.NumberFormat package.

Syntax:

Use NumberFormat’s provided syntax to round a double to two decimal places:

setMaximumFractionDigits(number);

Example:

First, a “nf” instance of the NumberFormat class will be created:

NumberFormat nf= NumberFormat.getInstance();

Call the setMaximumFractionDigits() function and pass “2” as an argument indicating the decimal point scale in a double value:

nf.setMaximumFractionDigits(2);

Also, the “format()” function will be used to output the rounded number after receiving the “dbl” input:

System.out.println("Updated rounded Double value: "+nf.format(dbl));

The working sample program:

import java.text.NumberFormat;

public class Example {

        public static void main(String[] args) {
                double dbl = 5214.1246;
                System.out.println("Original Double value: "+dbl);
                NumberFormat nf = NumberFormat.getInstance();
                nf.setMaximumFractionDigits(2);
                System.out.println("Updated rounded Double value is: "+nf.format(dbl));
        }
}

Output:

linuxhint@DESKTOP-XXXXXX:~$ java Example
Original Double value: 5214.1246
Updated rounded Double value is: 5,214.12

Method 5: Round a Double to two Decimal Places by Utilizing String format() Method

The “format()” method is the static method of the String class. This procedure functions like a “printf” instruction.

Syntax:

String.format("%.2f", doublevalue)

It takes two parameters, “%.2f” and the double value. The first parameter denotes the passed-in double value’s necessary format.

Example: We will call the String.format() method by passing the Double class object “dbl” and the format “%.2f” as its argument:

System.out.println("Updated rounded Double value: "+String.format("%.2f",dbl));

Here is the working program:

public class Example {

      public static void main(String[] args) {
           double dbl = 5215.1246;
           System.out.println("Original Double value: "+dbl);
           System.out.println("Updated rounded Double value is: "+String.format("%.2f", dbl));
      }
}

Output:

linuxhint@DESKTOP-XXXXXX:~$ java Example
Original Double value: 5215.1246
Updated rounded Double value is: 5215.12

Conclusion

Overall, rounding doubles in Java to two decimal places can be useful for improving readability, reducing errors, and saving resources when working with financial or other types of data that require high precision.

ONextdigital is a Vietnam-based Agile app development company that holds ISO certification. Our specialization includes mobile app consulting, design, and development for clients worldwide. We firmly believe in our ability to handle diverse project requests from clients, irrespective of their organizational field or market segment.

>> Read more:

IT Outsourcing Pros And Cons – Update 2023