×

Two Decimal Places Java

When a double data type is used in Java before a variable, this indicates 15 digits after decimal point. However, there are situations when we only require 2 decimal places after the decimal point, such as when representing rupees or other units. So, along with a suitable example and other Java applications, we will examine how to show double values with two decimal places in this part.

Java offers the three methods listed below for displaying double with two decimal places:

  1. Using the DecimalFormat ("0.00")
  2. Using the Method of String.format() ("%.2f")
  3. Using the BigDecimal

Let's go over each of these methods individually.

Using DecimalFormat Class

The NumberFormat class's concrete subtype, Java DecimalFormat, class is used to format decimal numbers. The setRoundingMode() method of the class enables the presentation of double numbers with up to two decimal places.

Syntax:

public void setRoundingMode(RoundingMode roundingMode) 

It overrides the setRoundingMode() function of the NumberFormat class and accepts the rounding mode as a parameter. If no roundingMode is specified, NullPointerException is thrown.

The format() function from the class DecimalFormat was also used by us. In order to create a string, it formats a string.

Syntax:

public StringBuffer format(double number, StringBuffer result, FieldPosition fieldPosition) 

Three inputs are taken into account by the method: number, result, and location. The latter two variables, however, are not required. The formatted string of numbers is what is returned. If roundingMode gets set to UNNECESSARY, the procedure throws an ArithmeticException.

TwoDecimalPlaceDemo1.java

import java.math.RoundMode;  
import java.text.TheDecimalFormat;  
public class TwoDecimalPlaceDemo1   
{  
// DecimalFormat class constructor
private static final TheDecimalFormat df = new TheDecimalFormat("0.00");  
public static void main(String args[])   
{  
// declaring a double-type number
double num = 123.9876543567;  
System.out.println("The Double Number is: " + numb);  
System.out.println("The Double Number is: " + df.format(numb));    //123.99  
//TheDecimalFormat, RoundingMode is the default. HALF EVEN
df.setRoundMode(RoundMode.DOWN);  
System.out.println("\nBefore The Rounding: " + df.format(numb));  //123.98  
df.setRoundMode(RoundMode.UP);  
System.out.println("After The Rounding Up: " + df.format(numb));    //123.99  
}  
}  

Output:

The Double Number is: 123.9876543567
The Double Number is: 123.99


Before The Rounding: 123.98
After The Rounding Up: 123.99

Using The Method String.format()

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

Lets use %.2f as format the number and change it to two decimal places. Note that using the String.format() function to round a number results in a half-up rounding.

Syntax:

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

Two parameters are accepted by the method:

format: We need a string that has been formatted.

args: The parameters which the format specifiers inside the format string are referring to are listed as args.

The formatted string is what it gives back. If the format string has unlawful syntax, it throws an IllegalFormatException. If the format is set to null, it also raises a NullPointerException.

TwoDecimalPlaceDemo2.java

public class TwoDecimalPlaceDemo2  
{  
public static void main(String args[])   
{  
// declaring a double-type number
double numb = 10.98765432167;  
System.out.println("The Double Number is: " + numb);  
// For two decimal places, you can choose from the following two statements, and both get the same outcome.
System.out.println("The Double Number is: " + String.format("%.2f", numb));  
System.out.format("The Double Number is: %.2f", numb);  
}  
}  

Output:

The Double Number is: 10.98765432167
The Double Number is: 10.99
The Double Number is: 10.99

Using the BigDecimal

For showing a number with one to two decimal places, we can alternatively utilise the Java BigDecimal Class. It is a part of Java.math. BigDecimal bundle It implements the ComparableBigDecimal> interface and extends the Number class.

The setScale() method is provided by the class. The following is the syntax:

setScale(int newScale, RoundingMode roundingMode)

The procedure accepts two of the parameters:

The newScale: The scaling of such BigDecimal value that will be returned is newScale.

The roundingMode: The rounding technique we intend to use.

It yields the BigDecimal for whom the unscaled value is calculated simply multiplication or division that BigDecimal's unoptimized values even by correction factors of ten to retain its overall value. The scale is the provided number.

If RoundingMode gets set to UNNECESSARY, the procedure throws the ArithmeticException. An enum that offers the RoundingMode mentioned above is called RoundingMode. BigDecimal is another technique we've employed in this program.

BigDecimal.doubleValue() is changed into a double number. Here's an illustration.

TwoDecimalPlaceDemo3.java

import java.math.TheBigDecimal;  
import java.math.RoundMode;  
public class TwoDecimalPlaceDemo3   
{  
public static void main(String args[])   
{  
// declaring a double-type number 
double numb = 12.4565652239;  
System.out.println("The Double Number is: " + numb);  
TheBigDecimal bigd = new TheBigDecimal(numb).setScale(2, RoundMode.HALF_UP);  
double newNumb = bigd.doubleValue();  
System.out.println("To the nearest two decimal places: " + newNumb);  
}  
}  

Output:

The Double Number is: 12.4565652239
To the nearest two decimal places: 12.46

Related Topics

Rehashing in Java

The most crucial idea mostly in the data structure is hashing, which is utilized to change a particular key into some other value. The hash function can be used to...

7 minutes read.

AbstractSet Class in Java

The AbstractSet class is used for the implementation of the Abstract Collection class and interface. It is the part of Collection Frameworks. In the AbstractSet, the implementation is same as the...

3 minutes read.

Java Byte Code

Java byte code is really a powerful mechanism which makes Java a portable and platform-independent programming language. There are two software components which go along and make this byte code...

3 minutes read.

Chromatic Number in Java

The chromatic number is the bare minimum of colours necessary to accurately colour any graph. To put it another way, the chromatic number can be thought of as the bare...

6 minutes read.

Java String getChars() Method

Java String getChars() method copies characters from current String to the destination character array . Syntax: public void getChars(int srcBeginIndex, int srcEndIndex, char[] destination, int dstBeginIndex) Parameters: srcBegin - index of the first character...

1 minute read.

Menu Driven Program in Java

Menu Driven Program in Java The menu-driven program in Java is a program that displays a menu and then takes input from the user to choose an option from the displayed...

3 minutes read.

&& Operator in Java

“ && ” is the conditional - And operator in Java. In Java, it is an example of a logical operator. In Java, the “ & ” operator has two...

3 minutes read.

Java Math with Methods and Examples

Java Math class contains various methods for performing math operations like min(), max(), avg() and various trigonometric functions like sin(), cos(), tan() etc. Methods: The java.lang.Math class contains various methods for performing...

5 minutes read.

RMI program in Java

Remote Method Invocation is what it stands for. An object can call the method of another object in a different space address using the RMI API, which may be on the...

3 minutes read.

Leap Year Program in Java

Leap Year Program in Java: A leap year is a calendar year that have an extra day i.e. 366 days instead of 365 days is called leap year. In other...

2 minutes read.

Zebra Puzzle Problem in Java

Complex puzzles like the zebra puzzle demand a lot of work and mental training to complete. Because it was created by renowned German scientist Albert Einstein, it is also sometimes...

10 minutes read.

Java Obfuscator

Obfuscation is the process of making something unclear or difficult to interpret. Obfuscators are being used in programming to protect the source code from hackers. In this article, we will...

8 minutes read.

Java ResultSetMetaData

The data about another data is called Metadata. The ResultSetMetaData is used to store the data about ResultSet. The ResultSet Contains the columns, rows, names of table, datatypes etc. these...

2 minutes read.

Union in Java

Sets.union() method in Java returns an immutable representation of both the union of two sets. Every element that is present in either backup set is included in the set that...

2 minutes read.

Median Of Stream Of Running Integers in Java

An integer array is given to us. Compute the median of the elements traversed so far in the input array. For the sake of simplicity, assume that there are no...

10 minutes read.

Minimum Number of Taps to Open to Water a Garden in Java

Problem Statement The issue is that a gardener wants to water a (single-dimensional) garden using the fewest possible tap openings. The goal is to determine the minimum necessary taps to be...

8 minutes read.

Hierarchy of operators in Java

Operators are the most frequently used terminology in any area of programming, and it helps in various approaches to efficiently solve daily life problems by computer programming. The simple addition of...

4 minutes read.

Java Get File Size

There are three ways to get the file size in Java. Using Java InputOutput Using NewInputOutput Library Files.size() Method FileChannel.size() Method Using Apache Commons InputOutput Using Java InputOutput: The Java IO package offers the classes that deal...

5 minutes read.

Java Float Keyword

Float: In general, there are two categories of data types: primitive data types and non-primitive data types. So, float is the data type which is a primitive data type. Declarating the variables and...

3 minutes read.

Java Integer getInteger() method

The getInteger() method of Integer class determines the integer value of the system property with the given name. Syntax` public static Integer getInteger(String nm) Parameters The parameter ‘nm’ represents the property name. Throws The getInteger ()...

1 minute read.