Sunday, September 23, 2007

Printing dollar amounts in Java

This is a very basic tutorial intended to help fix a lack of internet information my students mentioned.

Since it turns out finding out how to print dollar amounts from a dollar amount and a cent amount is not something that is easy to find on the internet, I though I'd make a post for googling.

Usually we want dollar amounts to come out something like $100.00, however if we call System.out.println("$" + dollar + "." + cents); we get $100.0.

To fix this, one way is to use the Formatter class from the Java 1.5 API. This class allows the use of C-printf style formatting in Java.

While I'm not going to dwell on all the formatting strings (see google), the one we want is %d.

To use formatter, the easiest way is demonstrated with the following test program (you can of course just call System.out.printf if you are only trying to print stuff -- this was to demonstrate how to get a string).



import java.util.Formatter;

public class pritf {

public static void main(String[] args) {
int num = 100;
int dec = 0;

Formatter printer = new Formatter();
String str = printer.format("$%d.%02d", num, dec).toString();
System.out.println(str);
}
}


Which outputs when run: $100.00

This ends my very short informative message. Google please point to this post.

Sean