×

How to Round Double Float up to Two Decimal Places in Java

It indicates 15 digits just after the decimal place in Java whenever a double data type is used in front of a variable. For example, when representing rupees and other units, we may only need two decimals just after the decimal point. 

Java offers the 3 techniques listed here to show double with two decimal places.

  • DecimalFormat is used ("0.00")
  • Making use of the String.format() Method ("%.2f")
  • BigDecimal is used.

Method 1: By using the DecimalFormat

The NumberFormat class's concrete subtype, Java DecimalFormat, is applied to print decimals. This setRoundingMode() function of the class enables the presentation of double numbers with up to two decimals.

The DecimalFormat class, a subclass of NumberFormat, is utilized in Java to format decimal integers. The format supplied in the form of #, with the amount of 0 just after the decimal point representing the number of digits you intend to print, is sent in as parameters when creating an object of this type. The amount is generally round to its maximum value. The format() function, which accepts the integer to be converted as an input, is called by the DecimalFormat class object.

Syntax:

public void setRoundingMode(RoundingMode roundingMode)  

It receives the rounded mode as an argument and modifies the setRoundingMode() function of the NumberFormat class. When no rounding mode is specified, NullPointerException is raised. 

TwoDecimal1.java

//this program is for rounding the decimal to 2 digits after the decimal place
//importing the required packages
import java.io.*;
import java.util.*;
import java.math.RoundingMode;  
import java.text.DecimalFormat;  
public class TwoDecimal1   
{  
// the constructor was created for the class TwoDecimal1      
private static final DecimalFormat decfors = new DecimalFormat("0.00");  
public static void main(String args[])   
{
// a decimal number was initialised
double nums = 12334.91381765423567;  
System.out.println("The Given Double Number is : " + nums);  
System.out.println("The Double Number is: " + decfors.format(nums));    //12334.91
decfors.setRoundingMode(RoundingMode.DOWN);  
System.out.println("\nThe number Before Rounding: " + decfors.format(nums));  //12334.91  
decfors.setRoundingMode(RoundingMode.UP);  
System.out.println("The number After Rounding Up: " + decfors.format(nums));    //12334.92  
}  
}  

Output

The Given Double Number is: 12334.913817654236
The Double Number is: 12334.91


Before Rounding: 12334.91
After Rounding Up: 12334.92

Dividing and multiplying the integer by 10n (n decimal places)

We first multiplied the value by 10n using the Math class' pow() function in this method. The amount is then reduced to the closest integer. The amount is finally divided by 10n. This allows us to obtain an integer value with n decimal points.

Syntax:

number = Math.round(number*Math.pow(10,n))/Math.pow(10,n);

Decimal.java

//this program is for rounding the decimal to 2 digits after the decimal place
//importing the required packages
import java.io.*;
// Main section of the program 
class Decimal{
//  Main section
public static void main(String[] args)
{


// a variable is initiallized
double num = 12.985665;


//  getting the input as the digits required after the decimal place
int places = 2;


//  the number is rounded off
// the methods are pow() and round() are used for rounding the number
num = Math.round(num * Math.pow(10, places))
/ Math.pow(10, places);


//  displaying the resultant number
System.out.println(num);
}
}

Output

12.99

Implementing the String.format() Method

The format() function is likewise available in Java for formatting numbers. It is a member of the String class. The technique allows for the appropriate formatting of any integer or text.

We format the integer using %.2f to change it up to two decimal points. Remember that using the String.format() function will result in a half-up round of the amount.

Syntax:

public static String format(String formats, Object... args) 

The following two arguments are accepted by the method:

format: What we need is a structured string.

args: The parameters listed in the formatting string's template constructors.

The converted string is returned. If the formatting string has improper syntax, it raises an IllegalFormatException. NullPointerException is also thrown if the formatting is null.

TwoDecimal3.java

//this program is for rounding the decimal to 2 digits after the decimal place
//importing the required packages
import java.io.*;
public class TwoDecimal3 
{  
public static void main(String args[])   
{  
// a number was declared
double nums = 101.923875465413;  
System.out.println(“The Given Double Number: " + nums);  
//The same answer may be obtained using either of the two additional expressions for the second decimal place.
System.out.println("The Double Number is : " + String.format("%.2f", nums));  
System.out.format("The formatted Double Number is: %.2f", nums);  
}  
}  

Output

The Given Double Number: is 101.923875465413
The Double Number is : 101.92
The formatted Double Number is: 101.92

By Using the BigDecimal

ma may also use Java's BigDecimal Class to show numbers with up to two decimal places. The java.math.BigDecimal package contains it. The ComparableBigDecimal> interface is implemented, subclasses the Numbers class.

The setScale() function is available from the class. This is how the sentence reads

Syntax:

setScale(int newScale, RoundingMode roundingMode)

The technique accepts two arguments:

newScale: The size of the given BigDecimal value.

rounding mode: The type of rounds that you wish to use.

It then provides the BigDecimal, which unoptimized amount is calculated by dividing or multiplication this BigDecimal's unoptimized value even by activation functions of ten to preserve its total value. The scale of the returned BigDecimal is the valuation supplied.

If RoundingMode is set as UNNECESSARY, the procedure raises an ArithmeticException. An enumeration called RoundingMode offers the RoundingMode mentioned before.

BigDecimal is a different approach that we've employed in this software.

doubleValue(). Another double number is created from BigDecimal.

Example:woDecimal4.java

//this program is for rounding the decimal to 2 digits after the decimal place
//importing the required packages
import java.io.*;
import java.math.BigDecimal;  
import java.math.RoundingMode;  
public class TwoDecimal4   
{  
public static void main(String args[])   
{  
// declaring the double number
double number = 121.49586585349;  
System.out.println("The Given Double Number is: " + number);  
BigDecimal bigd = new BigDecimal(number).setScale(2, RoundingMode.HALF_UP);
double newNume = bigd.doubleValue();  
System.out.println(" The required decimal number is: " + newNume);  
}  
}  

Output

The Given Double Number is: 121.49586585349
The required decimal number is: 121.5

Related Topics

Java Transient

Java Transient In Java, Serialization is used to convert an object into a stream of the byte. The byte stream consists of the data of the instance as well as the...

3 minutes read.

Class vs Object in Java

Java : Java is a pure object oriented language. It was introduced by James Gosling in the year 1995. The first public implementation of java was done by sun micro systems...

7 minutes read.

Blocking Queue in Java Example

Let's first briefly comprehend queue before moving on to the topic of "Blocking Queue." A queue seems to be an orderly list of items in which elements are added from...

8 minutes read.

How to Convert String to Date in Java

How to Convert String to Date in java You can convert String to Date in Java by using the parse() method. There are two classes which have parse() method namely, DateFormat and SimpleDateFormat classes....

2 minutes read.

Array and String based questions in Java

1. What is an Array in Java? A collection of identical data types is referred to as an array. There can be no separate data kinds. It supports the storage of...

4 minutes read.

Longest Odd Even Subsequence in Java

In order to solve the Java problem known as the longest odd-even subsequence, one must identify a sequences in a non-negative array having size s that alternately includes odd and...

6 minutes read.

Java Plot

Java Plot is a phrase in Java that is mostly used for plotting coordinates on a cartesian plane. Plotting graphs in Java is accomplished through the use of various core...

3 minutes read.

How to compare dates in Java

Introduction: In Java, dates can be compared using a similar interface's compareTo() technique. This method returns 'zero' if each date is the same, returns a rate "more than 0" if...

6 minutes read.

Java Set to List

In this article, you will be acknowledged about how the process of conversion from Set or HashSet to LinkedList happens and what are the possible ways involved in conversion process. First...

4 minutes read.

Number Pattern Programs in Java

Number Pattern Programs in Java: Number pattern programs are part of pattern programs. In the previous section, we have learned the approach to print the pattern program in Java. To...

6 minutes read.

How to add 6 Months to the Current Date in Java?

In this tutorial, we will learn how to add 6 months to the local or current date in Java language. We will begin our topic with basic concepts and would...

3 minutes read.

Java While Keyword

Depending on a specified Boolean condition, a while loop in Java allows code to be executed repeatedly. The while loop can be viewed as an iterative version of the if...

3 minutes read.

How to Solve the Deprecated Error in Java?

Deprecated Java methods should not be used because they are deprecated (often, there are better, more modern alternatives). API update. Until now, Java has kept everything backward compatible and never...

3 minutes read.

Pancake Sorting in Java

In the pancake sorting method, the array must be sorted using just one operation, which is: Flip the arrays arr at index 0 to index j by using flipArr(arr, h). Other sorting...

3 minutes read.

Why we use static in Java

Many reserved keywords in Java cannot be used as variable names or identifiers. Java uses static keywords frequently because of its effective memory management system. In most cases, you must...

3 minutes read.

This Operator Using in Java

this keyword in Java has a wide range of applications. this reference variable in Programming language refers to the object of interest. This keyword is used in Java. this keyword is...

5 minutes read.

Singleton Design Pattern in Java

In the singleton pattern, a class that only has one instance and offers a universal point of access is taken into consideration. It can also be defined in another way, a...

4 minutes read.

Memory Areas in Java

Let’s have a look at how memory management in Java works. We will be going to discuss how the objects get destroyed, the working of a garbage collector, and things...

5 minutes read.

Java List Node

In Java, List Node is the same as the single linked list, which is the collection of nodes. So, we can say, the list nodes are grouped together to get...

8 minutes read.

Java calculate age

In this section, we will create a Java program that calculates age from the given date of birth or current date. In order to get the date of birth from the current...

6 minutes read.