• Status: Solved
• Priority: Medium
• Security: Public
• Views: 2826

# Parse amount field using regular expression

I have an HTML input field for entering an amount. It must be 1 to 20 digits, optionally followed by up to 10 decimal digits, and optionally ending with "k" or "m" to denote the thousand or million respectively. So "123.12k" would be parsed as 123120. The following is a JavaScript solution previously provided by Tim Yates:

function mFunc( sVal )
{
var elems = sVal.match( /^(\d{1,20}(\.\d{0,10})?)([k|m])?\$/ ) ;
if( elems )
{
var num = elems[ 1 ] ;
var mult = elems[ 3 ] ;
if( mult == 'k' )
{
num *= 1000 ;
}
else if( mult == 'm' )
{
num *= 1000000 ;
}
alert( 'value is ' + num ) ;
}
else
{
alert( 'invalid number' ) ;
}
}

Now I need the equivalent function in Java. Thanks!
0
yongsing
1 Solution

Commented:
this should work as long it is OK to use BigDecimal, because only this type of object can hold 30 meaningfull digits

also import
java.math.BigDecimal;
java.util.regex.*;

public BigDecimal mFunc(String sVal) {
Pattern p = Pattern.compile("^(\\d{1,20}(\\.\\d{0,10})?)([kKmM])?\$");
Matcher m = p.matcher(sVal);
if(m.matches()) {
BigDecimal num = new BigDecimal(m.group(1));
if(m.group(3) != null) {
if(m.group(3).equalsIgnoreCase("k"))
num = num.multiply(new BigDecimal("1000"));
else if(m.group(3).equalsIgnoreCase("m"))
num = num.multiply(new BigDecimal("1000000"));
}
return num;
} else
throw new NumberFormatException("Invalid number");
}

0

Commented:
Thanks, that looks good. I will try it out.
0

## Featured Post

Tackle projects and never again get stuck behind a technical roadblock.