Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
403 views
in Technique[技术] by (71.8m points)

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). 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.

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

Thanks.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)
String newStr = oldStr.replaceAll("[^\d.]+", "")

This will drop any character that is not either a digit or a period


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...