在欧洲,小数与'
,
'我们使用可选'
.
“把成千上万的人分开。我允许货币价值:
美式123456.78符号
欧洲风格123.456,78符号
我使用下一个正则表达式(来自RegexBuddy库)来验证输入。我允许可选的两位小数和可选的千位分隔符。
^[+-]?[0-9]{1,3}(?:[0-9]*(?:[.,][0-9]{0,2})?|(?:,[0-9]{3})*(?:\.[0-9]{0,2})?|(?:\.[0-9]{3})*(?:,[0-9]{0,2})?)$
我想将货币字符串解析为浮点。例如
123456.78应存储为123456.78
123.456,78应存储为123456.78
123.45应存储为123.45
1.234应存储为1234
12.34应存储为12.34
等等…
在Java中有一种简单的方法吗?
public float currencyToFloat(String currency) {
// transform and return as float
}
使用bigdecimal而不是float
感谢大家的回答。我已经将代码改为使用bigdecimal而不是float。我将保持这个问题的前一部分浮动,以防止人们做同样的错误,我要做。
解决方案
下一个代码显示一个函数,该函数将美国和欧盟货币转换为BigDecimal(字符串)构造函数接受的字符串。也就是说,一个没有千位分隔符的字符串和一个分数点。
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class TestUSAndEUCurrency {
public static void main(String[] args) throws Exception {
test("123,456.78","123456.78");
test("123.456,78","123456.78");
test("123.45","123.45");
test("1.234","1234");
test("12","12");
test("12.1","12.1");
test("1.13","1.13");
test("1.1","1.1");
test("1,2","1.2");
test("1","1");
}
public static void test(String value, String expected_output) throws Exception {
String output = currencyToBigDecimalFormat(value);
if(!output.equals(expected_output)) {
System.out.println("ERROR expected: " + expected_output + " output " + output);
}
}
public static String currencyToBigDecimalFormat(String currency) throws Exception {
if(!doesMatch(currency,"^[+-]?[0-9]{1,3}(?:[0-9]*(?:[.,][0-9]{0,2})?|(?:,[0-9]{3})*(?:\\.[0-9]{0,2})?|(?:\\.[0-9]{3})*(?:,[0-9]{0,2})?)$"))
throw new Exception("Currency in wrong format " + currency);
// Replace all dots with commas
currency = currency.replaceAll("\\.", ",");
// If fractions exist, the separator must be a .
if(currency.length()>=3) {
char[] chars = currency.toCharArray();
if(chars[chars.length-2] == ',') {
chars[chars.length-2] = '.';
} else if(chars[chars.length-3] == ',') {
chars[chars.length-3] = '.';
}
currency = new String(chars);
}
// Remove all commas
return currency.replaceAll(",", "");
}
public static boolean doesMatch(String s, String pattern) {
try {
Pattern patt = Pattern.compile(pattern, Pattern.CASE_INSENSITIVE);
Matcher matcher = patt.matcher(s);
return matcher.matches();
} catch (RuntimeException e) {
return false;
}
}
}