在歐洲,小數點以','分隔,我們使用可選的'。'分隔數千。我允許與貨幣價值:如何解析貨幣金額(美國或歐盟)在Java中的浮動值
- 美國式123,456.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})?)$
我想解析一個貨幣字符串爲浮動。例如
123,456.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的,而不是浮點
感謝大家的偉大的答案。我已經改變我的代碼使用BigDecimal而不是浮動。我會將這個問題的前一部分保留爲float,以防止人們犯同樣的錯誤。
解
下一個代碼示出了從美國和歐盟貨幣轉換到通過的BigDecimal(String)構造接受字符串的函數。這是說一個沒有千分位的分數和一個分數的字符串。
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;
}
}
}
那麼1.23轉換爲什麼?你的規則是矛盾的。爲什麼不利用客戶端應用程序中的本地化設施? – spender 2009-06-08 16:47:19
1.23轉換爲1.23 – 2009-06-08 16:48:53
好的,我的壞...但真的,試圖破譯這不知道它來自哪裏的地方有一種難聞的氣味。 – spender 2009-06-08 16:50:08