import java.text.DecimalFormat;
import java.math.BigDecimal;

public class TwoPlaces {
  public static void main(String[] args) {
    double cents = 0.20 + 0.05 + 0.01 + 0.01 + 0.01 + 0.01 + 0.01;
    
    // System.out.printf mimics the printf command from the
    // C programming language.  It is based on an arcane
    // formatting language.  See pp. 257-261 in the book.
    System.out.printf("%.2f should look better than %f\n", cents, cents);
    
    // Using DecimalFormat has reliability and simplicity.
    // You only need to assign twoPlaces once.
    DecimalFormat twoPlaces = new DecimalFormat("#0.00");
    System.out.println(twoPlaces.format(cents) +
                       " probably looks better than " + cents );
    
    // Convert number of pennies to a long, then divide by 100.
    // This is the least reliable method for nice printing.
    double roundedCents = (long) Math.round(100 * cents) / 100.0;
    System.out.println(roundedCents + " might look better than "
                      + cents);
    
    // Using BigDecimal is more complex, but it allows you to do
    // arithmetic in decimal.
    BigDecimal centsDecimal = new BigDecimal(cents);
    BigDecimal roundedCentsDecimal =
      centsDecimal.setScale(2, BigDecimal.ROUND_HALF_EVEN);
    System.out.println(roundedCentsDecimal + " is nicer than "
                      + centsDecimal);
  }
}

