- Data Structure
- Networking
- RDBMS
- Operating System
- Java
- MS Excel
- iOS
- HTML
- CSS
- Android
- Python
- C Programming
- C++
- C#
- MongoDB
- MySQL
- Javascript
- PHP
- Physics
- Chemistry
- Biology
- Mathematics
- English
- Economics
- Psychology
- Social Studies
- Fashion Studies
- Legal Studies
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Java Program to round a double passed to BigDecimal
The java.math.BigDecimal class provides operations for arithmetic, scale manipulation, rounding, comparison, hashing, and format conversion.
Firstly, let us pass a double to BigDecimal −
BigDecimal val = new BigDecimal(9.19456);
Now, we will round it −
val = val.setScale(2, BigDecimal.ROUND_HALF_EVEN);
Above, we have used the field ROUND_HALF_EVEN. It is a rounding mode to round towards the "nearest neighbor" unless both neighbours are equidistant, in which case, round towards the even neighbours
The following is an example −
Example
import java.math.BigDecimal; public class Demo { public static void main(String args[]) { BigDecimal val = new BigDecimal(9.19456); val = val.setScale(2, BigDecimal.ROUND_HALF_EVEN); System.out.println(val); } }
Output
9.19
Advertisements