26 April 2005

Java Formatting Currency and Dates

The easiest way to display a double in the local currency is to get an instance of NumberFormat currency formatter and use its format() method. The following example ...
import java.text.NumberFormat;

public class CurrencyFormatExample {
  public static void main(String[] argv) {
    NumberFormat cf = NumberFormat.getCurrencyInstance();
    double cost = 19.51;
    System.out.println("Cost = " + cf.format(cost));
... produces ...
Cost = $19.51
Similarly, the easiest way to display a date is to get an instance of a DateFormat date formatter and use its format() method. Choose different types of date formatters to produce shorter or longer output. The following example creates four different data formatters ...
import java.text.DateFormat;
import java.util.Date;

public class DateFormatExample {
  public static void main(String[] argv) {
    DateFormat dfShort = DateFormat.getDateInstance(DateFormat.SHORT);
    DateFormat dfMedium = DateFormat.getDateInstance(DateFormat.MEDIUM);
    DateFormat dfLong = DateFormat.getDateInstance(DateFormat.LONG);
    DateFormat dfFull = DateFormat.getDateInstance(DateFormat.FULL);
    Date today = new Date();
    System.out.println("Today is ...");
... and produces ...
Today is ...
26 April 2005
Tuesday, 26 April 2005

21 April 2005

Misc: Robust self serve petrol process

It was a busy evening at the Shell. I had to wait to refuel because one of the bowsers in my line wasn't working. Then I had to join a long queue to pay because there was only one cashier. "Pump 4, please," I said to the cashier when I reached the counter. The cashier looked puzzled. "Are you sure? It's been paid." I went out and double-checked. "Yep, it's 4." We worked out that someone else had paid the wrong bowser (mine) and since his or her amount was less than mine, I paid for the petrol from the other bowser and count myself lucky. Why don't customers pay the wrong bowser more often? Attendents can't match the person paying to the bowser. Perhaps by evolution, the self serve process is robust because:
  1. You can't pay for a bowser that is still pumping, so you have to quote a bowser that is both idle and not paid.
  2. If you quote the wrong bowser number, the person who used that bowser is probably in the shop and would hear you.
So, the incident happened because it was busy, the other person finished quickly, paid my bowser when I had just finished but I hadn't yet walked into the shop.