Showing posts with label tips. Show all posts
Showing posts with label tips. Show all posts

Monday, 18 January 2010

Proper way to compare java.math.BigDecimal

import java.math.BigDecimal;
import java.math.MathContext;

public class BigDecimalTest {

 public static void main(String[] args) {
  
  System.out.println(new BigDecimal(0).equals(BigDecimal.ZERO));
  System.out.println(new BigDecimal("0").equals(BigDecimal.ZERO));
  System.out.println(new BigDecimal(0.0d).equals(BigDecimal.ZERO));
  System.out.println(new BigDecimal(0.0f).equals(BigDecimal.ZERO));
  
  //WTF
  System.out.println(new BigDecimal("0.0").equals(BigDecimal.ZERO)); // false!!!
  System.out.println(new BigDecimal("0.0").equals(new BigDecimal("0"))); // false!!!
  System.out.println(new BigDecimal("0.0").equals(new BigDecimal(0.0))); // false!!!
  
  //same is with "1" and "1.0", and so on

  //That's not a precision problem
  MathContext mc = new MathContext(2);
  System.out.println(new BigDecimal("0.0", mc).equals(new BigDecimal(0.0, mc))); // false!!!
  
  //So, the proper way to compare two big decimals is:
  System.out.println(new BigDecimal("0.0").compareTo(BigDecimal.ZERO) == 0); 
 }
The answer lies in API docs: BigDecimal#equals.

Wednesday, 13 January 2010

Make Eclipse faster by limiting number of open editor tabs

Eclipse can close tabs automatically. This improves performance, saves memory and keeps your workspace cleaner.

  1. Open Preferences
  2. Go to General > Editors 
  3. Set "Number of opened editors before closing" to something small. I use 8.
  4. Apply and enjoy