| Start |
|---|
| Comparing BigDecimals The method Commonly you should not use the |
| Using BigDecimal instead of float Due to way that the float type is represented in computer memory, results of operations using this type can be inaccurate - some values are stored as approximations. Good examples of this are monetary calculations. If high precision is necessary, other types should be used. e.g. Java 7 provides BigDecimal. Output of this program is: For a starting balance of 10000.00, after 1000 operations for 1.99, we expect the balance to be 8010.00. Using the float type gives us an answer around 8009.77, which is unacceptably imprecise in the case of monetary calculations. Using BigDecimal gives us the proper result. |
| Mathematical operations with BigDecimal This example shows how to perform basic mathematical operations using BigDecimals. 1.AdditionResult : 12 2.SubtractionResult : -2 3.MultiplicationWhen multiplying two Result : 36.89931 To change the scale of the result use the overloaded multiply method which allows passing Result : 36.90 4.DivisionDivision is a bit more complicated than the other arithmetic operations, for instance consider the below example: We would expect this to give something similar to : 0.7142857142857143, but we would get: Result: java.lang.ArithmeticException: Non-terminating decimal expansion; no exact representable decimal result. This would work perfectly well when the result would be a terminating decimal say if I wanted to divide 5 by 2, but for those numbers which upon dividing would give a non terminating result we would get an For example, I could do: Result : 0.7142857143 5.Remainder or ModulusResult : 5 6.PowerResult : 9765625 7.MaxResult : 7 8.MinResult : 5 9.Move Point To LeftResult : 52.3449843776 10.Move Point To RightResult : 5234498.43776 There are many more options and combination of parameters for the above mentioned examples (For instance, there are 6 variations of the divide method), this set is a non-exhaustive list and covers a few basic examples. |
| BigDecimal.valueOf() The BigDecimal class contains an internal cache of frequently used numbers e.g. 0 to 10. The BigDecimal.valueOf() methods are provided in preference to constructors with similar type parameters i.e. in the below example a is preferred to b. |
| Initialization of BigDecimals with value zero, one or ten BigDecimal provides static properties for the numbers zero, one and ten. It's good practise to use these instead of using the actual numbers:
By using the static properties, you avoid an unnecessary instantiation, also you've got a literal in your code instead of a 'magic number'. |
| BigDecimal objects are immutable If you want to calculate with BigDecimal you have to use the returned value because BigDecimal objects are immutable: |
Read Article
https://develop.horje.com/learn/1434/reference