Home » Core Java » Java Round Number to N Decimal Places Example Vipul is a Senior Software Engineer with experience in different software technologies including Java, Javascript, Angular, React, Material Design, databases (MySQL), HTML/CSS and even AWS, Big Data and Machine Learning. He likes learning new technologies and using the latest libraries in his work.

# Java Round Number to N Decimal Places Example

In this example, we are going to show how we can round a decimal number in Java. Before going in details let us brief you about what exactly is the rounding a number means.

## 1. What is rounded Number

A rounded number has about the same value as the original number we started with. It is less exact than the original value but is simpler, shorter, easy to communicate and report. Example: 73 rounded to the nearest ten is 70 because 73 is closer to 70 than to 80. But 76 goes up to 80 because it is closer to 80 than to 70.

## 2. Why we should round a number

Let’s take an example.

Mike has his birthday next week and he is planning for a birthday party. So wanted to know how many pieces of cake he needs. After counting all his friends he came to know it is a total of 192 people will be coming and decided to have 200 pieces of cake so that it will be enough for 192 people. So what Mike did just he rounded the number 192 to 200.

Another example could be you wanted to pay the taxes and you calculate it as \$1.7894. So you will round it at \$1.79. right?

If you’re talking about the population of a City, it’s easier to say 12 million people rather than a more exact figure of 12,224,425 people.

Doing some calculation in the head instead of doing it with a number 6.97 we can do it with 7 in a very easier way.

Likewise, there may be so many reasons to round a number.

From the above discussion, We came to know that we can round both natural numbers (e.g. 192, 12,224, 425, etc) as well as a fraction or decimal numbers (e.g. 1.79, 6.97, etc.).

## 3. How do we round the numbers

Here is a very simple and commonly used method to round numbers and is called half_up rounding

1. Identify which is the last digit to keep (rounding digit)
2. See if next digit is less than 5 then leave rounding digit same (round down) and if it is greater than or equal to 5 increase the rounding digit by one (round_up)
3. Finally, replace the digits after the rounding digit with zero (or leave them off completely if rounding a decimal).

## 4. Writing Java program

Since now we have an understanding of how to round a decimal number, Let’s see how many ways we can do the same in Java

### 4.1 Setting up the project

We should you maven for all our project so that if any dependent jar is required we should be able to package it in a pom.xml file.

Setup a maven project in eclipse or any IDE of your choice. In Eclipse Goto File-> new -> maven project Create a maven project

Select create a simple maven project skip archetype selection checkbox

Fill all the necessary details for the project to be created as below

• Group Id: can be anything and is mandatory but recommended to follow the package name rules, which means that has to be at least as a domain name you control. E.g. com.javacodegeeks
• Artifact Id: Can be anything and is mandatory It is the name of the jar without version. E.g. examples
• Version: you can choose normal version naming rules. E.g 1.0, 1.1…
• Project Name: Optional. E.g. JCG Examples
• Description: Optional.

Add below Dependency in pom.xml file

junit dependency
```<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.10</version>
<scope>test</scope>
</dependency>```

Create a Java Class `DecimalNumberRounder` under `com.javacodegeeks.examples` packege.

Add a class in `DecimalNumberRounderTest` in `com.javacodegeeks.examples` in `src/test/java` folder

DecimalNumberRounder.java
```package com.javacodegeeks.examples;

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

public class DecimalNumberRounder {
public static double roundNumbers(double number, int places) {

double scale = Math.pow(10, places);
return Math.round(number * scale) / scale;
}

public static double roundUsingBigDecimal(double number, int places) {
BigDecimal x = BigDecimal.valueOf(number).setScale(places, RoundingMode.HALF_UP);
return x.doubleValue();
}

public static double roundUsingStringFormator(double number, int places) {
return Double.parseDouble(String.format("%." + places + "f", number));
}
}
```

Explanation: Lots of code, here is the explanation of what we are doing in above code…

1. In the first method `roundNumbers()` we are using a naive approach using `Math.round()` the inbuilt method from java and controlling n number of decimal places by multiplying and dividing by 10^n.
2. In the second method `roundUsingBigDecimal()` we are using `BigDecimal` class and setting `scale` and `mode` to be used while rounding the value. finally returning converted double value.
3. In the third method, `roundUsingStringFormator()` we are simply formatting the input value to n decimal places and then returning the same by converting it to double value.

### 4.3 Writing JUnit Test Cases

Now lets Add some Junit tests for the class

DecimalNumberRounderTest.java
```package com.javacodegeeks.examples;

import static org.junit.Assert.assertTrue;

import org.junit.Test;

public class DecimalNumberRounderTest {

@Test
public void roundNumbersTest() {
assertTrue(DecimalNumberRounder.roundNumbers(123.4567, 3) == 123.457);
assertTrue(DecimalNumberRounder.roundNumbers(123.4564, 3) == 123.456);
assertTrue(DecimalNumberRounder.roundNumbers(123.4567, 2) == 123.46);
}

@Test
public void roundUsingBigDecimalTest() {
assertTrue(DecimalNumberRounder.roundUsingBigDecimal(123.4567, 3) == 123.457);
assertTrue(DecimalNumberRounder.roundUsingBigDecimal(123.4564, 3) == 123.456);
assertTrue(DecimalNumberRounder.roundUsingBigDecimal(123.4567, 2) == 123.46);
}

@Test
public void roundUsingStringFormatorTest() {
assertTrue(DecimalNumberRounder.roundUsingStringFormator(123.4567, 3) == 123.457);
assertTrue(DecimalNumberRounder.roundUsingStringFormator(123.4564, 3) == 123.456);
assertTrue(DecimalNumberRounder.roundUsingStringFormator(123.4567, 2) == 123.46);
}
}
```

Explanation:

Here we are using JUnit which is an open-source testing framework for Java

1. `@Test`: specifies that the method is a test method.
2. `assertTrue(boolean condition)`: checks that a condition is true.
3. Here we have written test cases for all three methods for three scenarios.

### 4.4 Running JUnit Test

Now lets run the JUnit Test for our project right click on project > run as > JUnit Test

### 4.5 Result

As we can see in the results all the test methods are getting passed. So we have written a fully functional code to round a number to n decimal places.

## 6. Bonus Points

### 6.1 Using Apache Commons Math Library

We can use Commons Math: The Apache Commons Mathematics Library which is a library of lightweight, self-contained mathematics and statistics components addressing the most common problems not available in the Java programming language or Commons Lang. We have to add below dependency in `pom.xml` file

commons-math3 dependency
```<dependency>
<groupId>org.apache.commons</groupId>
<artifactId>commons-math3</artifactId>
<version>3.6.1</version>
<scope>test</scope>
</dependency>```

Now we can write the same functionality as…

```Precision.round(123.4567, 3);
Precision.round(123.4564, 3);
Precision.round(123.4567, 2);
```

### 6.2 Using decimal4j library

We can also use decimal4j library for fast fixed-point arithmetic based on longs with support for up to 18 decimal places. We have to add below dependency in `pom.xml` file

decimal4j dependency
```<dependency>
<groupId>org.decimal4j</groupId>
<artifactId>decimal4j</artifactId>
<version>1.0.3</version>
<scope>test</scope>
</dependency>```

And now…

```DoubleRounder.round(123.4567, 3);
DoubleRounder.round(123.4564, 3);
DoubleRounder.round(123.4567, 2);
```

This was an example of Round Number to N Decimal Places.
You can download the full source code of this example here: Java Round Number to N Decimal Places Example  (+3 rating, 3 votes)
Start the discussion Views Tweet it!

# Do you want to know how to develop your skillset to become a Java Rockstar?

## Subscribe to our newsletter to start Rocking right now!

### and many more .... 