BeginnersBook

  • Home
  • Java
    • Java OOPs
    • Java Collections
    • Java Examples
  • C
    • C Examples
  • C++
    • C++ Examples
  • DBMS
  • Computer Network
  • Python
    • Python Examples
  • More…
    • jQuery
    • Kotlin
    • WordPress
    • SEO
    • JSON
    • JSP
    • JSTL
    • Servlet
    • MongoDB
    • XML
    • Perl

How to round a number to two decimal places in Java

Last Updated: May 31, 2024 by Chaitanya Singh | Filed Under: java

In Java, you can round double and float numbers to two decimal places using several different approaches. Let’s see some java programs to see how can we achieve this.

1. Using Math.round

We already covered this method in detail at: Java Math.round() method. Since, we are dealing with two decimal places, you can simply multiply the number by 100, round it to the nearest integer, and then divide by 100. This method works for both double and float numbers.

public class RoundExample {
public static void main(String[] args) {
double doubleValue = 143.456789; //double
float floatValue = 143.456789f; //float

double roundedDouble = Math.round(doubleValue * 100.0) / 100.0;
float roundedFloat = Math.round(floatValue * 100.0f) / 100.0f;

// Output: 143.46
System.out.println("Rounded double: " + roundedDouble);
// Output: 143.46
System.out.println("Rounded float: " + roundedFloat);
}
}

2. Using BigDecimal

Another wonderful method to round double and float to two decimal places is using BigDecimal. In this approach, there are two main steps:

1. Convert double/float to BigDecimal:

//double to BigDecimal
BigDecimal bdDouble = new BigDecimal(Double.toString(doubleValue));
//float to BigDecimal
BigDecimal bdFloat = new BigDecimal(Float.toString(floatValue));

First step is to convert the given double and float values to BigDecimal. This can be done using Double.toString() method.

2. Set Scale and Rounding Mode:

bdDouble = bdDouble.setScale(2, RoundingMode.HALF_UP);
bdFloat = bdFloat.setScale(2, RoundingMode.HALF_UP);

setScale(2, RoundingMode.HALF_UP) sets the scale of the BigDecimal to 2 decimal places.RoundingMode.HALF_UP is the rounding mode that rounds towards “nearest neighbour” unless both neighbours are at equal distance, in which case it rounds up. For example, 2.555 becomes 2.56, and 2.554 becomes 2.55.

Let’s see the complete program:

import java.math.BigDecimal;
import java.math.RoundingMode;

public class RoundExample {
public static void main(String[] args) {
double doubleValue = 143.456789;
float floatValue = 143.456789f;

// Convert double to BigDecimal
BigDecimal bdDouble = new BigDecimal(Double.toString(doubleValue));
bdDouble = bdDouble.setScale(2, RoundingMode.HALF_UP);

// Convert float to BigDecimal
BigDecimal bdFloat = new BigDecimal(Float.toString(floatValue));
bdFloat = bdFloat.setScale(2, RoundingMode.HALF_UP);

// Output: 143.46
System.out.println("Rounded double: " + bdDouble.doubleValue());
// Output: 143.46
System.out.println("Rounded float: " + bdFloat.floatValue());
}
}

3. Using String.format

Let’s see the third approach to round a number to two decimal places. In this method, we will use String.format method. In the following program, In the format specifier %.2f, the f indicates decimal while point (.2) indicates the two decimal places. This method returns a String representation of the rounded number.

public class RoundExample {
public static void main(String[] args) {
double doubleValue = 143.456789;
float floatValue = 143.456789f;

String roundedDouble = String.format("%.2f", doubleValue);
String roundedFloat = String.format("%.2f", floatValue);

// Output: 143.46
System.out.println("Rounded double: " + roundedDouble);
// Output: 143.46
System.out.println("Rounded float: " + roundedFloat);
}
}

4. Using DecimalFormat

In this approach, we create an instance of DecimalFormat with the pattern #.00. The pattern #.00 indicates that the number should have at least one digit before the decimal point and exactly two digits after the decimal point.

import java.text.DecimalFormat;

public class RoundExample {
public static void main(String[] args) {
double doubleValue = 143.456789;
float floatValue = 143.456789f;

DecimalFormat df = new DecimalFormat("#.00");

String roundedDouble = df.format(doubleValue);
String roundedFloat = df.format(floatValue);

// Output: 143.46
System.out.println("Rounded double: " + roundedDouble);
// Output: 143.46
System.out.println("Rounded float: " + roundedFloat);
}
}
❮ Java Math

Top Related Articles:

  1. Java Math.min() Method
  2. Java Integer equals() Method
  3. Java Integer divideUnsigned() Method
  4. How to set Path in Java
  5. Java Integer byteValue() Method

Tags: Java Math

About the Author

I have 15 years of experience in the IT industry, working with renowned multinational corporations. Additionally, I have dedicated over a decade to teaching, allowing me to refine my skills in delivering information in a simple and easily understandable manner.

– Chaitanya

Leave a Reply Cancel reply

Your email address will not be published. Required fields are marked *

Java Tutorial

Java Introduction

  • Java Index
  • Java Introduction
  • History of Java
  • Features of Java
  • C++ vs Java
  • JDK vs JRE vs JVM
  • JVM - Java Virtual Machine
  • First Java Program
  • Variables
  • Data Types
  • Operators

Java Flow Control

  • Java If-else
  • Java Switch-Case
  • Java For loop
  • Java while loop
  • Java do-while loop
  • Continue statement
  • break statement

Java Arrays

  • Java Arrays

OOPs Concepts

  • OOPs Concepts
  • Constructor
  • Java String
  • Static keyword
  • Inheritance
  • Types of inheritance
  • Aggregation
  • Association
  • Super Keyword
  • Method overloading
  • Method overriding
  • Overloading vs Overriding
  • Polymorphism
  • Types of polymorphism
  • Static and dynamic binding
  • Abstract class and methods
  • Interface
  • Abstract class vs interface
  • Encapsulation
  • Packages
  • Access modifiers
  • Garbage Collection
  • Inner classes
  • Static import
  • Static constructor

Java Exception Handling

  • Exception handling
  • Java try-catch
  • Java throw
  • Java throws
  • Checked and Unchecked Exceptions
  • Jav try catch finally
  • Exception Examples
  • Exception Propagation

Collections Framework

  • Collections in Java
  • Java ArrayList
  • Java LinkedList
  • Java Vector
  • Java HashSet
  • Java LinkedHashSet
  • Java TreeSet
  • Java HashMap
  • Java TreeMap
  • Java LinkedHashMap
  • Java Queue
  • Java PriorityQueue
  • Java Deque
  • Comparable interface
  • Comparator interface
  • Collections Interview Questions

MORE ...

  • Java Scanner Class
  • Java 8 Features
  • Java 9 Features
  • Java Conversion
  • Java Date
  • Java Multithreading
  • Java I/O
  • Java Serialization
  • Java Regex
  • Java AWT
  • Java Swing
  • Java Enum
  • Java Annotations
  • Java main method
  • Java Interview Q

Copyright © 2012 – 2025 BeginnersBook . Privacy Policy . Sitemap