
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
Working with BigDecimal Values in Java
The java.math.BigDecimal class provides operations for arithmetic, scale manipulation, rounding, comparison, hashing, and format conversion.
Two types of operations are provided for manipulating the scale of a BigDecimal −
- scaling/rounding operations
- decimal point motion operations
The following are some of the constructors of the BigDecimal values −
Sr.No. | Constructor & Description |
---|---|
1 |
BigDecimal(BigInteger val) This constructor is used to translates a BigInteger into a BigDecimal. |
2 |
BigDecimal(BigInteger unscaledVal, int scale) This constructor is used to translate a BigInteger unscaled value and an int scale into a BigDecimal. |
3 |
BigDecimal(BigInteger unscaledVal, int scale, MathContext mc) This constructor is used to translate a BigInteger unscaled value and an int scale into a BigDecimal, with rounding according to the context settings. |
4 |
BigDecimal(BigInteger val, MathContext mc) This constructor is used to translate a BigInteger into a BigDecimal rounding according to the context settings. |
5 |
BigDecimal(char[ ] in) This constructor is used to translate a character array representation of a BigDecimal into a BigDecimal, accepting the same sequence of characters as the BigDecimal(String) constructor. |
6 |
BigDecimal(char[ ] in, int offset, int len) This constructor is used to translate a character array representation of a BigDecimal into a BigDecimal, accepting the same sequence of characters as the BigDecimal(String) constructor, while allowing a sub-array to be specified. |
The following is an example −
Example
import java.math.BigDecimal; public class Demo { public static void main(String[] argv) throws Exception { BigDecimal val1 = new BigDecimal("37578975.8768"); BigDecimal val2 = new BigDecimal("62567878.9768"); BigDecimal val3 = new BigDecimal("72567874.3768"); System.out.println("Value 1 : "+val1); System.out.println("Value 2 : "+val2); val1 = val1.add(val2); System.out.println("Addition Operation = " + val1); val1 = val1.multiply(val2); System.out.println("Multiplication Operation = " + val1); val2 = val3.subtract(val2); System.out.println("Subtract Operation = " + val2); val2 = val3.divide(val2,BigDecimal.ROUND_UP); System.out.println("Division Operation = " + val2); } }
Output
Value 1 : 37578975.8768 Value 2 : 62567878.9768 Addition Operation = 100146854.8536 Multiplication Operation = 6265976294387200.48179648 Subtract Operation = 9999995.4000 Division Operation = 7.2568
Advertisements