A common task in any programming language, especially for students, is to convert a double or a float into a properly round and formatted decimal format appropriate for use as currency. There are two rather discrete steps in this process. The first step is to round the number appropriately. When working with currency people tend to get upset if you just start truncating numbers rather than rounding them correctly. So we will start by doing this. Then we will format the number for simple display as currency.
Rounding for Currency
// Let's make some doubles to get us started.
double unroundedNumber = 1435.4587;
double roundedNumber = 0;
// Multiply by 100 to move the decimal point to the right two digits
unroundedNumber = unroundedNumber * 100;
// Java's Math.round() method rounds to the nearest integer
roundedNumber = Math.round(unroundedNumber);
// Move the decimal point back to the left two digits
roundedNumber = roundedNumber / 100;
System.out.print(roundedNumber);
Formatting for Currency
Now that we have a nicely and accurately rounded number to work with we can work on displaying it. Manual formatting is, of course, an option but Java includes a class designed for this function and why not leverage the hard work that SUN has already done for us? Not only does Java do very nice, automatic formatting but it also has built in internationalization features. Let’s explore!
// First we need to instantiate a NumberFormat object and declare our locality (US for me)
NumberFormat nf = NumberFormat.getCurrencyInstance(Locale.US);
System.out.println(nf.format(roundedNumber));