
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Round Number to Fewer Decimals in Java
Let’s say we need to round number to 3 decimal places, therefore use the following format −
DecimalFormat decFormat = new DecimalFormat("0.000");
Now, format the number −
decFormat.format(37878.8989)
Since we have used the DecimalFloat class above, therefore do import the following package −
import java.text.DecimalFormat;
The following is an example that rounds a number to 3 decimal places −
Example
import java.text.DecimalFormat; public class Demo { public static void main(String[] args) { DecimalFormat decFormat = new DecimalFormat("0.000"); System.out.println("Result = " + decFormat.format(37878.8989)); } }
Output
Result = 37878.899
Let us see another example that rounds a number to 5 decimal places −
Example
import java.text.DecimalFormat; public class Demo { public static void main(String[] args) { System.out.println(String.format("Result = %.5f", 76576.696799)); } }
Output
Result = 76576.69680
Advertisements