Number formatting is a refinement that many programming languages do not automatically provide. For instance, I’ve often come across applications and web pages that display large numbers in a rather ugly and unreadable form:
Total profits for 1997 were $1673824183.
If only the program would add a few commas, this number would be much more readable. And sometimes—for example, when I want my programs to write checks or other legal documents—I need a mechanism that will allow me to output numbers in text form:
We recorded five thousand, seven hundred, and eighteen people at the
conference.
Java, like many other programming languages, lacks tools that produce comma-delimited or textual numbers. Such number formatting isn’t terribly difficult to implement, though, and I’ve provided a pretty good solution with my FormatNumbers class.
package coyote.math;
//
//
//hFormatNumbers
//
//
public class FormatNumbers
{
//-----------------------
// Constants
//-----------------------
static final char [] DIGIT =
{
'0', '1', '2', '3', '4', '5', '6', '7', '8', '9'
};
static final String [] ONES =
{
"", "one", "two", "three", "four", "five", "six",
"seven", "eight", "nine", "ten", "eleven",
"twelve", "thirteen", "fourteen", "fifteen",
"sixteen", "seventeen", "eighteen", "nineteen"
};
static final String [] TENS =
{
"twenty", "thirty", "forty", "fifty",
"sixty", "seventy", "eighty", "ninety"
};
static final String [] POWERS =
{
"thousand", "million", "billion", "trillion",
"quadrillion", "quintillion"
};
//-----------------------
// Fields
//-----------------------
private char m_cSeparator;
private char m_cCurrency;
private int m_nGroupLen;
//-----------------------
// Class methods
//-----------------------
// Return 10 raised to the power p
private static int pow10(int p)
{
int res;
for (res = 1; --p >= 0; res *= 10);
return res;
}
// Integer logarithm (determines magnitude of an int)
private static int log10(int l)
{
int p;
for (p = 9; 0 == (l / pow10(p)); --p);
return p;
}