/**
* convert a String into long pennies.
* It ignores invalid chars, lead trail, embedded spaces.
* Dash is treated as a minus sign.
* 0 or 2 decimal places are permitted.
*
* @param numStr String to be parsed.
*
* @return long in pennies.
*
* @exception NumberFormatException if the number is too big to fit in a long.
*/
public static long parseLongPennies( String numStr )
{
numStr = numStr.trim ();
StringBuffer b = new StringBuffer( numStr.length() );
boolean negative = false;
int decpl = -1;
for ( int i=0; i<numStr.length(); i++ )
{
char c = numStr.charAt( i );
switch ( c )
{
case '-' :
negative = true;
break;
case '.' :
if ( decpl == -1 )
{
decpl = 0;
}
else
{
throw new NumberFormatException( "more than one decimal point" );
}
break;
case '0' :
case '1' :
case '2' :
case '3' :
case '4' :
case '5' :
case '6' :
case '7' :
case '8' :
case '9' :
if ( decpl != -1 )
{
decpl++;
}
b.append(c);
break;
default:
break;
}
}
if ( numStr.length() != b.length() )
{
numStr = b.toString();
}
if ( numStr.length() == 0 )
{
return 0;
}
long num = Long.parseLong( numStr );
if ( decpl == -1 || decpl == 0 )
{
num *= 100;
}
else if ( decpl == 2 )
{
}
else
{
throw new NumberFormatException( "wrong number of decimal places." );
}
if ( negative )
{
num = -num;
}
return num;
}
/**
* convert pennies to a string with a decorative decimal point.
* @param long amount in pennies.
* @return amount with decorative decimal point, but no lead $.
*/
public final static String penniesToString ( long pennies )
{
boolean negative;
if ( pennies < 0 )
{
pennies = -pennies;
negative = true;
}
else
{
negative = false;
}
String s = Long.toString( pennies );
int len = s.length();
switch ( len )
{
case 1:
s = "0.0" + s;
break;
case 2:
s = "0." + s;
break;
default:
s = s.substring ( 0, len-2 ) + "." + s.substring( len-2, len );
break;
}
if ( negative )
{
s = "-" + s;
}
return s;
}