简体   繁体   English

在java中解析货币字符串

[英]Parsing a currency String in java

Suppose I'm supplied with a String which is like "$123,456,56.25" or "123'456.67" or something similar to this (with digits and a decimal point and some seperator like , or ' or something else which is not predictable). 假设我提供的字符串类似于"$123,456,56.25" "123'456.67" "$123,456,56.25""123'456.67"或类似的东西(带有数字和小数点以及某些分隔符,'或其他不可预测的东西)。 I need to write a method which takes an argument like the one above and returns a String like "12345656.25" or "123456.67" respectively. 我需要编写一个方法,它接受类似上面的参数并分别返回一个字符串,如"12345656.25""123456.67"

Could you please suggest the most efficient and readable code to achieve this? 能否请您提出最有效和最易读的代码来实现这一目标?

Note: I'm aware of going through each indexes and checking for whether its retunrs true for Character.isDigit(charAtInedx) or if(charAtInedx == '.') I'm looking for a more optimized solution both in terms of efficiency and readability 注:我知道的,通过各项指标去,并检查其是否retunrs trueCharacter.isDigit(charAtInedx)或者if(charAtInedx == '.')我无论是在效率方面寻找一个更优化的解决方案,可读性

Thanks. 谢谢。

String newStr = oldStr.replaceAll("[^\\d.]+", "")

这将删除任何不是数字或句点的字符

If you want to handle monetary values correctly, you will want to have a look at the NumberFormat class, specifically for your case NumberFormat.parse(String) . 如果要正确处理货币值,您需要查看NumberFormat类,特别是您的CaseFormat.parse(String) The following article also discusses the problems (and solutions) to handling money in Java: 以下文章还讨论了在Java中处理资金的问题(和解决方案):

http://www.javapractices.com/topic/TopicAction.do?Id=13 http://www.javapractices.com/topic/TopicAction.do?Id=13

Other related classes include: Currency and of course BigDecimal . 其他相关类包括: 货币 ,当然还有BigDecimal

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM