Tutorial by Examples: bigdecimal

If you want to calculate with BigDecimal you have to use the returned value because BigDecimal objects are immutable: BigDecimal a = new BigDecimal("42.23"); BigDecimal b = new BigDecimal("10.001"); a.add(b); // a will still be 42.23 BigDecimal c = a.add(b); // c will be ...
The method compareTo should be used to compare BigDecimals: BigDecimal a = new BigDecimal(5); a.compareTo(new BigDecimal(0)); // a is greater, returns 1 a.compareTo(new BigDecimal(5)); // a is equal, returns 0 a.compareTo(new BigDecimal(10)); // a is less, returns -1 Commonly you shou...
This example shows how to perform basic mathematical operations using BigDecimals. 1.Addition BigDecimal a = new BigDecimal("5"); BigDecimal b = new BigDecimal("7"); //Equivalent to result = a + b BigDecimal result = a.add(b); System.out.println(result); Result : 12 ...
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 Big...
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. BigDecimal a = BigDecimal.valueOf(10L); //Returns cached O...
BigDecimal provides static properties for the numbers zero, one and ten. It's good practise to use these instead of using the actual numbers: BigDecimal.ZERO BigDecimal.ONE BigDecimal.TEN By using the static properties, you avoid an unnecessary instantiation, also you've got a literal in you...

Page 1 of 1