Monday, August 2, 2021

4 Examples to Round Floating-Point Numbers in Java up to 2 Decimal Places

Rounding numbers up to 2 or 3 decimal places id a common requirement for Java programmers. Thankfully, Java API provides a couple of ways to round numbers in Java. You can round any floating-point numbers in Java unto n places By using either Math.round(), BigDecimal, or DecimalFormat. I personally prefer to use BigDecimal to round any number in Java because of it's convenient API and support of multiple Rounding modes. Also, if you are working in the financial industry, it's best to do a monetary calculation in BigDecimal rather than double as I have discussed in my earlier post about common Java mistakes

One of the important things to keep in mind while rounding numbers is Rounding mode. Rounding mode decides how to round discarded fractions and knowledge of popular rounding modes like HALF DOWN, HALF UP, and HALF EVEN certainly helps.

We have seen some bits to round numbers in How to format numbers in Java using the DecimalFormat, and in this Java article, we will explore a couple of more ways to round numbers up-to 2 digits in Java.

Though, if you are new to Java, I suggest you first start learning basics like data types, float vs long, and float vs double before going into the tricky topic of rounding numbers in Java. If you need a resource then I highly recommend you join these free Core Java courses. It's also the most up-to-date course and covers new Java features from recent releases.





4 ways to Round floating-point Numbers in Java 

Without wasting any more of your time, here are 4 different ways of rounding numbers in Java. They use RoundingMode and DecimalFormat class in Java for formatting floating-point numbers and rounding them up to two decimal places.

1. Rounding Modes in Java

An important thing to know before rounding numbers is rounding mode. In general, programmers things that if the least significant digit is less than five, then it will be rounded to the floor, greater than five than towards the ceiling, and they get confused when it's equidistant.

Rounding modes decide how the least significant digit should be rounded. The BigDecimal class has a Rounding mode defined as an integer constant, which was later replaced by RoundingMode enum from Java 1.5. Here are some of the important RoundingMode to remember :
  1. RoundingMode.HALF_DOWN: round down if both neighbors are equidistant like 2.5 will round to 2.0
  2. RoundingMode.HALF_UP: round up if both neighbors are same distance like 2.5 will round to 3.0
  3. RoundingMode.HALF_EVEN: round towards even neighbor if both neighbors are equidistant like 2.5 will round to 2.0 while 5.5 will round to 6.0
There is a couple of more Rounding mode as well like UP, DOWN, FLOOR, and CEILING, which is also worth knowing. If you want to learn more about floating-point numbers and these concepts, I suggest you join these core Java courses beginners. It's a great fundamental course for Java developers.

4 Examples to Round  Floating Point Numbers in Java up to 2 Decimal Places



2. Round number to 2 decimal place using BigDecimal

Whenever I need to round a number up to n decimal places, I first think of BigDecimal. Not only BigDecimal allow you to choose RoundingMode, but also it's very easy to round numbers up to any decimal place using BigDecimal methods. Here is an example of rounding numbers up to 2 decimal places :

float number = BigDecimal.valueOf(digit)
                         .setScale(2, BigDecimal.ROUND_HALF_DOWN)
                         .floatValue();

In setScale(), you can specify the number of decimal places you need to round like to round up to 5 places specify 5. Here we have set the scale as 2 because we are rounding up to 2 digits. We have also used rounding mode as ROUND_HALF_DOWN, which is similar to RoundingMode.HALF_DOWN.

Half down rounding mode will round numbers down if the discarded fraction is 0.5. In place of BigDecimal.ROUND_HALF_DOWN, you can also use RoundingMode.HALF_DOWN but just beware that RoundingMode enum was added from Java 5 onwards.

Of course, you know this because Java Enum was introduced in the 1.5 version. If you are using Java 1.4, then this is the right way to round numbers up to 2 decimals in Java. Btw, if you want to learn more about Java Enum and other key concepts, you can also take a look at the Java Programming for Complete Beginners course on Udemy.



3. Round number to 2 digits using DecimalFormat

If you are rounding numbers just for displaying purposes then you should consider using DecimalFormat or String format method class. Though there is nothing wrong with using BigDecimal to round numbers, DecimalFormat seems to be the right class for formatting numbers.

Here is Java code to round a number up to 2 significant digits using DecimalFormat in Java.

DecimalFormat df = new DecimalFormat("#.00");
float number = Float.valueOf(df.format(decimal));

The #.00 is for rounding up to 2 decimal places, if you want to round up to 3 or 4 places, just use #.000 or #.0000 to create DecimalFormat. To know more about formatting numbers, See How to format numbers in Java using DecimalFormat.



4. Round number in Java using Math.round()

The Math.round() was classical ways to round numbers in Java. Though it doesn't provide any API to specify how many digits to round, by using multiplication and division, you can make it round up to n or 2 decimal places.

By the way, this is not the preferred way to round numbers in Java, I prefer BigDecimal, but still, its a convenient way to round numbers and works in many cases. Here is How to use Math.round() function to round numbers up to 2 digits in Java.

float rounded = (float) Math.round(number100)/100;

We are multiplying and later dividing by 100 to round up to 2 digits if you need to round up to 5 decimal places, multiply and divide by 100000.

By the way, it's Java best practice to prefer BigDecimal over Math.round() to round numbers in Java and if you want to learn more of such Java Practices then there is no better book than Effective Java by Joshua Bloch, it's a great book for both beginners and experienced Java developers. Though,  If you have already read that then you can also try Java by Comparison by Simon Harrer and others.

best book for experienced Java developers




Java program to round numbers up to 2 decimal places

Here is a Java program that combines above 3 ways to round any number up to 2 decimal places in Java. You can change the program to round up to 3, 4, or any number of digits.

import java.math.BigDecimal; 
import java.math.RoundingMode; 
import java.text.DecimalFormat; 
import java.util.Arrays;
 
  
/** 
  * Java program tor round numbers up to 2 decimal places in Java.
   * This program explains 3 ways to round numbers, including BigDecimal, 
   * Math.round and DecimalFormat class.
   * @author javin paul
   */
 
public class RoundingNumbers {
 
 
 
    public static void main(String args[]) {
  
         //Sample floating point numbers to round upto 2 decimal places
         float[] samples = new float[]{2.123f, 2.125f, 2.127f};
 
   
        //using Match.round() function to round number upto 2 decimal place
         float[] rounded = round(samples);
 
  
        System.out.println("Before rounding, original numbers        : " 
                              + Arrays.toString(samples));
        System.out.println("After rounding using Math.round() method : " 
                              + Arrays.toString(rounded));
 
 
 
        //Using BigDecimal to round a number up to two decimal place
 
        //You can use different rounding modes e.g., HALF_UP, HALF_DOWN,
          and HALF_EVEN with BigDecimal
 
        rounded = roundUsingBigDecimal(samples);
 
 
 
        System.out.println("Before rounding numbers                  : "
                               + Arrays.toString(samples));
 
        System.out.println("After rounding number using BigDecimal   : " 
                               + Arrays.toString(rounded));
 
 
        //DecimalFormat Example to round number to 2 digits
         rounded = roundUsingDecimalFormat(samples);
         System.out.println("Original floating point numbers          : " 
                             + Arrays.toString(samples));
         System.out.println("round numbers with DecimalFormat in Java : "
                              + Arrays.toString(rounded));
   
    }
 
 
    /*
     * round number to 2 decimal place using Math.round
     */
 
    public static float[] round(float[] numbers){
 
        float[] round = new float[numbers.length];
 
        for(int i = 0; i            float number = numbers[i];

                //rounding number to 2 decimal place
                round[i] = (float) Math.round(number100)/100; 
        }
        return round;      
    }
 
    /*
     * round number to 2 decimal place using BigDecimal class
     * BigDecimal here uses ROUND_HALF_DOWN rounding mode
     */
    public static float[] roundUsingBigDecimal(float[] digits){
        float[] result = new float[digits.length];
        for(int f=0; f            float digit = digits[f];
            result[f] = BigDecimal.valueOf(digit)
                                  .setScale(2, BigDecimal.ROUND_HALF_DOWN)
                                  .floatValue();
        }
        return result;
    }
 
    /*
     * rounding number to 2 decimal place using DecimalFormat
     */
    public static float[] roundUsingDecimalFormat(float[] decimals){
        float[] rounded = new float[decimals.length];
        //DecimalFormat to round numbers to 2 decimal place 
        DecimalFormat df = new DecimalFormat("#.00"); 
        for(int i=0; i            float decimal = decimals[i];
            rounded[i] = Float.valueOf(df.format(decimal));
        }
        return rounded;
    } 
 
}
 
Output:
Before rounding, original numbers        : [2.123, 2.125, 2.127]
After rounding using Math.round() method : [2.12, 2.13, 2.13]
Before rounding numbers                  : [2.123, 2.125, 2.127]
After rounding number using BigDecimal   : [2.12, 2.12, 2.13]
Original floating-point numbers          : [2.123, 2.125, 2.127]
round numbers with DecimalFormat in Java : [2.12, 2.12, 2.13]


That's all on How to round a number up to 2 decimal places in Java. We have seen 3 ways to round numbers in Java, like BigDecimal, DecimalFormat, and Math.round(). BigDecimal looks like the best way to round numbers because of the convenient API and support of different rounding modes.


Other Java and Programming Resources you may like
  • The Complete Java Developer RoadMap (roadmap)
  • 10 Things Java Programmer should learn (things)
  • 10 Books Every Programmer Must Read (books)
  • 10 Tools Every Software Developer should know (tools)
  • 5 Courses to Learn Software Architecture in Depth (courses)
  • 10 Courses to learn DevOps in Depth (courses)
  • 10 Tips to Improve Your Programming skill (tips)
  • 20 Libraries Java Programmer Should Know (libraries)
  • Top 10 Programming languages to Learn (languages)
  • 10 Courses to learn Java in-depth (courses)
  • 10 Framework and Library Java and Web Developer Should Learn (frameworks)
  • Top 5 Courses to Learn Microservice in Java (course)
Thanks for reading this article so far. If you find this article useful and able to understand essential OOP concepts like overloading, overriding, hiding, shadowing, and obscuring them please share with your friends and colleagues on Facebook, Twitter, or Linkedin. If you have any questions or doubt then please drop a note.

P. S. - If you are new to the Java Programming world and want to learn Java but looking for a free course then you can also check out this list of 10 Free Java Programming websites for beginners and anyone who wants to learn Java. 

1 comment:

  1. Thanks a lot, the first solution is perfect, it saved my Day. Another advice I would like to give fellow developer is that always use double if you are dealing with numbers like in billion even if you are rounding percentage into two digits. float is not appropriate for dealing with larger numbers. Using double will save you a lot of headache like instead of 1500000000 you may get 149999999999 when using float.

    ReplyDelete

Feel free to comment, ask questions if you have any doubt.