Monday, December 1, 2008

Weekly Source Code: Get Cents

Part of making changes to the Java currency to words code I pass in a double value parameter to the convert method (not a long) and add support for cents e.g. : $5.20 to equal "Five USD and Twenty cents".

An interesting problem I had was how do I get the cents part? e.g. $5.20 to get 20.

Firstly I had to format the number to round off to the last 2 digits so something like $5.2555 will not work. To do this in Java you can use the DecimalFormat class.

To get the cents I wrote:

double cents = new Double(new Double(number).doubleValue() - new Double(number).intValue()).doubleValue();
int iCents = (int) Math.round(cents * 100d);

The first line of code take the double value and subtract the integer value e.g. 5.20 - 5.0 = 0.20
The second line format the remaining value 0.20 to be an integer e.g. 20

Like always there are many ways in programming how this could be done and yes the above code works 100% since I wrote a very detail Unit test.

1 comment:

Asava Samuel said...

This is a great FTP Library for C#, it is reasonably priced too: