4 Examples To Round Floating-Point Numbers In Java Up To ... - Java67

Pages

  • Home
  • core java
  • spring
  • online courses
  • thread
  • java 8
  • coding
  • sql
  • books
  • oop
  • interview
  • certification
  • free resources
  • best
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.

3 comments:

  1. AnonymousOctober 25, 2021 at 2:40 AM

    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.

    ReplyDeleteReplies
      Reply
  2. AnonymousMay 17, 2022 at 7:14 AM

    Thanks a lot! I helped a lot!

    ReplyDeleteReplies
    1. javin paulMay 18, 2022 at 9:47 PM

      My pleasure

      DeleteReplies
        Reply
    2. Reply
Add commentLoad more...

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

Newer Post Older Post Home Subscribe to: Post Comments (Atom)

Recommended Courses

  • best python courses
  • best java courses
  • system design courses
  • best spring courses
  • best hibernate courses
  • best design pattern courses
  • best Linux courses
  • best JavaScript courses
  • best data structure and algorithms courses
  • Best Multithreading Courses
  • best MERN stack courses
  • Best Git courses
  • Best Microservice Courses
  • Best DevOps Courses
  • best MEAN stack Courses
  • free Java courses
  • free DSA courses
  • free sql courses
  • free Linux courses
  • Free Docker courses
  • free JUnit courses

Categories

  • .NET
  • abstract class
  • ActiveMQ
  • Affiliate marketing
  • After Effects
  • Agentic AI
  • Agile
  • AI Tools
  • Amazon Web Service
  • android
  • Angular
  • Anonymous class
  • Ansible
  • apache camel
  • Apache kafka
  • Apache spark
  • app development
  • array
  • ArrayList
  • Artificial Intelligence
  • automation
  • aws
  • aws certification
  • Azure Certifications
  • backend development
  • bash
  • basics
  • beginners
  • best of java67
  • best practices
  • Big Data
  • binary tree
  • bit manipulation
  • black friday deals
  • Blockchain
  • BlockingDeque
  • books
  • Bootstrap
  • business analysis
  • ByteByteGo
  • C programming
  • C++
  • Career
  • ChatGPT
  • Chef
  • cloud certification
  • Cloud Computing
  • Code Example
  • Code Review
  • codecademy
  • Codemia
  • CodeRabbit
  • coding
  • coding exercise
  • Coding Interview
  • Coding Problems
  • Comparator
  • computer science
  • Computer Vision
  • concurrency tutorial
  • ConcurrentHashMap
  • core java
  • core java interview question answer
  • course review
  • Coursera
  • courses
  • crontab
  • CSS
  • Cyber Monday
  • Cyber Security
  • Data Analysis
  • data science
  • data structure and algorithm
  • Data Visualization
  • database
  • datacamp
  • date and time
  • debugging
  • deep learning
  • default methods
  • design pattern
  • DevOps
  • DevSecOps
  • Distributed Systems
  • Django
  • docker
  • double
  • Drawing
  • DSA
  • dyanmic programming
  • dynamic Programming
  • eBooks
  • Eclipse
  • EJB
  • enum
  • equals
  • error and exception
  • Ethical hacking
  • Excel
  • exception
  • Exponent
  • expressjs
  • FAANG
  • Figma
  • Firebase
  • flatmap
  • float
  • Flutter
  • free resources
  • freelancing
  • Frontend Masters
  • fun
  • Fundamental
  • fundamentals
  • Game development
  • garbage collection
  • general
  • Generics
  • gifts
  • git and github
  • golang
  • Google Cloud Certification
  • Google Cloud Platform
  • Gradle
  • grails
  • graph
  • graphic design
  • grep
  • Groovy
  • gRPC
  • Hadoop
  • HashMap
  • HashSet
  • haskell
  • Hibernate
  • Hibernate interview Question
  • homework
  • HTML
  • HTTP
  • HttpClient
  • i
  • interface
  • Internet of Things (IoT)
  • interview
  • interview questions
  • IT Certification
  • J2EE
  • Jackson
  • java
  • Java 5 tutorial
  • java 7
  • Java 8
  • java 9
  • java basics
  • Java Certification
  • Java collection tutorial
  • java concurrency tutorial
  • java design pattern
  • Java Enum
  • Java file tutorials
  • Java Functional Programming
  • Java Installation Guide
  • Java Interview Question
  • Java interview questions
  • Java IO interview question
  • java io tutorial
  • java map tutorials
  • java modules
  • Java Multithreading Tutorial
  • Java networking tutorial
  • Java Operator tutorial
  • Java programming Tutorial
  • Java String tutorial
  • Java7
  • JavaScript
  • JavaScript Interview Question
  • JavaScript Tutorial
  • JDBC
  • JEE Interview Questions
  • Jenkins
  • JMS
  • JPA
  • jQuery
  • JSON
  • JSP
  • JSP Interview Question
  • JSTL
  • JUnit
  • JVM
  • Keras
  • keystore
  • Kotlin
  • kubernetes
  • lambda expression
  • Laraval
  • learning
  • linked list
  • Linux
  • Log4j
  • logging
  • Lombok
  • LSAT
  • Mac OS X
  • machine learning
  • Mathematics
  • Matlab
  • Maven
  • MERN stack
  • Messaging
  • Microservices
  • Microsoft
  • Microsoft Azure Platform
  • Microsoft Excel
  • Microsoft Power BI
  • Mockito
  • MongoDB
  • MysQL
  • MySQL tutorial example
  • nested class
  • neural network
  • Next.js
  • NFT
  • NLP
  • Node.js
  • nslookup
  • object oriented programming
  • OCAJP
  • OCMJEA
  • OCPJP
  • offers
  • Oracle
  • Perl
  • personal development
  • Photoshop
  • PHP
  • pluralsight
  • PostgerSQL
  • postman
  • Powerpoint
  • programmers
  • programming
  • programming problems
  • Project Management
  • projects
  • Prompt Engineering
  • Proxy
  • Python
  • Pytorch
  • Quarkus
  • questions
  • Queue
  • R programming
  • RabbitMQ
  • React
  • React Hooks
  • react native
  • Record
  • Recursion
  • Redux
  • regular expression example
  • REST tutorials
  • Review
  • RoadMap
  • Ruby
  • Salesforce
  • SAT
  • Scala
  • Scala Interview Questions
  • Scalability
  • Scanner
  • scripting
  • Scrum
  • Scrum Master Certification
  • Selenium
  • SEO
  • Serialization
  • Servlet
  • Servlet Interview Questions
  • Set
  • shell scripting
  • smart contracts
  • Snowflake SnowPro Certification
  • soft link
  • soft skills
  • software architecture
  • Solaris
  • Solidity
  • Sorting Algorithm
  • Spark
  • spring boot
  • Spring Certification
  • spring cloud
  • spring data jpa
  • spring framework
  • spring interview question
  • spring mvc
  • spring security
  • sql
  • SQL interview Question
  • SQL Joins
  • SQL SERVER
  • ssl
  • Static
  • Statistics
  • Stream
  • String
  • Struts
  • Swift
  • swing
  • switch case
  • system design
  • System Design Interview Questions
  • Tableau
  • Tailwind
  • TensorFlow
  • ternary operator
  • testing
  • thread
  • thread interview questions
  • Time series analysis
  • Tips
  • tomcat
  • tools
  • tree
  • TreeMap
  • troubleshooting
  • TypeScript
  • Udacity
  • Udemy
  • UI and UX Design
  • UML
  • unit testing
  • Unity 3D
  • Unix
  • unreal engine
  • Video Editing
  • Vuejs
  • web design
  • web development
  • web scrapping
  • Web Service
  • Whizlabs
  • Wix
  • xml
  • YAML
  • ZTM Academy

Best System Design and Coding Interview Resources

System Design & Interview Prep

  • ByteByteGo Lifetime Plan (50% OFF)
  • Codemia Lifetime Plan (60% OFF)
  • Exponent Annual Plan (70% OFF)
  • Educative Premium Plus (55% OFF)
  • DesignGurus All Course Bundle (55% OFF)
  • Everything Java Interview Bundle (50% OFF)
  • 101 Blockchain (50% OFF)
  • Vlad Mihalcea's High Performance Bundle (50% OFF)
  • Javarevisited Substack Subscription (50% OFF)
  • Head First Software Architecture (Book)

Search This Blog

Best Online Learning Resources and Platforms

  • Coursera Plus (40% OFF)
  • Datacamp Sale (50% OFF)
  • AlgoMonster Lifetime Plan (50% OFF)
  • Udemy Sale (80% OFF)
  • Baeldung (33% OFF)
  • LabEx Sale (50% OFF)
  • Codecademy Sale (60% OFF)
  • Udacity Sale (50% OFF)
  • ZTM Academy Sale (66% OFF)
  • Frontend Masters Deal
  • Whizlabs Deal (70% OFF)

Javarevisited

Loading...

Spring Interview Prep List

  • Spring Boot Interview questions
  • Spring Cloud Interview questions
  • Spring MVC Interview Questions
  • Microservices Interview questions
  • 10 Spring MVC annotations
  • Spring Boot Courses
  • Spring Framework Courses

Subscribe for Discounts and Updates

Follow

Interview Questions

  • core java interview questions
  • SQL interview questions
  • data structure interview question
  • coding interview questions
  • java collection interview questions
  • java design pattern interview questions
  • thread interview questions
  • hibernate interview questions
  • j2ee interview questions
  • Spring Interview Questions
  • object oriented programming questions

Followers

Blog Archive

  • ▼  2021 (104)
    • ▼  August (31)
      • Java 8 Stream filter() + findFirst Example Tutorial
      • How to add and remove Elements from an Dynamic Arr...
      • Top 20 Java EE Web Developer Interview Questions
      • How to Remove Objects From ArrayList while Iterati...
      • 9 JSP Implicit Objects and When to Use Them
      • How to Enable GC Logging in Java HotSpot JVM
      • Some JavaScript Tips
      • 4 Ways to Write String to File in Java
      • How to use Expression language in JSP - Example
      • jQuery pseudo selector Example
      • jQuery DOM Traversal example
      • How to select and change multiple lines in SSMS (S...
      • Exception in thread thread_name: java.lang.OutOfMe...
      • How to use Randam vs ThreadLocalRandom vs SecureRa...
      • How to use Stream.filter method in Java 8? Example...
      • 3 ways to ignore null fields while converting Java...
      • What is difference between final vs finally and fi...
      • How to prepare Oracle Certified Master Java EE Ent...
      • How to use Record in Java? Example
      • What is the cost of Oracle Java Certifications - O...
      • Top 3 Free Struts Books for Java EE developers - L...
      • Difference between VARCHAR and NVARCHAR in SQL Server
      • How to implement Comparator and Comparable in Java...
      • Difference between List <?> and List<Object> in J...
      • Java - Difference between getClass() and instanceo...
      • How to Read or Parse CSV files with Header in Java...
      • Can You Run Java Program Without a Main Method? [I...
      • What is double colon (::) operator in Java 8 - Exa...
      • 4 Examples to Round Floating-Point Numbers in Java...
      • How to Attach Apache Tomcat Server in Eclipse fo...
      • Top 5 Java 8 Default Methods Interview Questions a...

Privacy

  • Privacy Policy
  • Terms & Conditions

Popular Posts

  • 17 Free Java Programing Books for Beginners in 2025 - download, pdf and HTML
  • How to fix "illegal start of expression" error in Java? Example
  • 5 Examples of Formatting Float or Double Numbers to String in Java
  • Top 10 Websites to Learn JavaScript Coding for FREE in 2025 - Best of Lot
  • Top 10 Frequently asked SQL Query Interview Questions Answers

Subscribe

Get new posts by email:
Subscribe

Tag » How To Round Up Java