Item 60: Avoid float and double if exact answers are required

Use BigDecimal, int, or long for monetary calculations instead of float and double types

Advantages of using BigDecimal

  • You want to have full control over rounding
  • You don’t mind keeping track of the decimal point
  • You don’t mind the inconvenience and cost of not using a primitive type

Disadvantages to using BigDecimal

  • Less convenient than using a primitive arithmetic type
  • A lot slower

An alternative to using BigDecimal is to use “int” or “long”, if you wan’t to keep track of the decimal point yourself

  • If the quantities don’t exceed nine decimal digits, use int
  • If the quantities exceed eighteen digits, use long
  • If the quantities might exceed eighteen digits, use BigDecimal

Leave a Reply

Your email address will not be published. Required fields are marked *