4 Examples To Round Floating-Point Numbers In Java Up To ... - Java67
Maybe your like
Pages
- Home
- core java
- spring
- online courses
- thread
- java 8
- coding
- sql
- books
- oop
- interview
- certification
- free resources
- best
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 :- RoundingMode.HALF_DOWN: round down if both neighbors are equidistant like 2.5 will round to 2.0
- RoundingMode.HALF_UP: round up if both neighbors are same distance like 2.5 will round to 3.0
- 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
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.
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)
3 comments:
AnonymousOctober 25, 2021 at 2:40 AMThanks 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
AnonymousMay 17, 2022 at 7:14 AMThanks a lot! I helped a lot!
ReplyDeleteReplies
javin paulMay 18, 2022 at 9:47 PMMy pleasure
DeleteReplies- Reply
Reply
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
FollowInterview 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
- ► 2026 (21)
- ► February (14)
- ► January (7)
- ► 2025 (554)
- ► December (3)
- ► November (9)
- ► October (72)
- ► September (18)
- ► July (71)
- ► June (103)
- ► May (67)
- ► April (25)
- ► March (18)
- ► February (79)
- ► January (89)
- ► 2024 (192)
- ► December (30)
- ► October (32)
- ► September (31)
- ► August (12)
- ► July (3)
- ► June (2)
- ► May (9)
- ► April (3)
- ► March (28)
- ► February (3)
- ► January (39)
- ► 2023 (380)
- ► December (1)
- ► November (2)
- ► October (4)
- ► September (154)
- ► August (12)
- ► July (23)
- ► May (9)
- ► April (116)
- ► March (15)
- ► February (35)
- ► January (9)
- ► 2022 (164)
- ► December (18)
- ► October (1)
- ► September (1)
- ► August (45)
- ► July (27)
- ► June (11)
- ► May (19)
- ► April (16)
- ► March (12)
- ► February (6)
- ► January (8)
- ► 2020 (10)
- ► August (2)
- ► July (1)
- ► June (1)
- ► April (3)
- ► March (1)
- ► February (2)
- ► 2019 (9)
- ► December (1)
- ► November (1)
- ► October (1)
- ► September (1)
- ► July (1)
- ► June (1)
- ► April (3)
- ► 2018 (9)
- ► November (1)
- ► April (8)
- ► 2017 (4)
- ► October (1)
- ► September (2)
- ► April (1)
- ► 2015 (8)
- ► July (1)
- ► June (1)
- ► May (1)
- ► February (5)
- ► 2012 (1)
- ► September (1)
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:
SubscribeTag » How To Round Up Java
-
Rounding Of Numbers In Java - Vertex Academy
-
Java Round Up Any Number - Math - Stack Overflow
-
How To Round Up In Java - Linux Hint
-
Round Up A Number In Java | Delft Stack
-
How To Round Up In Java Code Example
-
How To Use The Java Math.round() Method
-
How To Round A Number To N Decimal Places In Java - Baeldung
-
How To Round Up To 2 Decimal Places In Java? - Intellipaat Community
-
Java Math Round() - Programiz
-
How Do I Round A Decimal To Nearest Integer In Java? - Quora
-
Java Math Round() Method With Example - GeeksforGeeks
-
Java Program To Round A Number To N Decimal Places
-
Java Math.round() Method With Examples - Javatpoint
-
Round Up Int [Solved] (Beginning Java Forum At Coderanch)
Anonymous
javin paul