Java 从字符串中删除美元和逗号
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/20351323/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Removing Dollar and comma from string
提问by Varun Vishnoi
How can we remove dollar sign ($) and all comma(,) from same string? Would it be better to avoid regex?
我们如何从同一个字符串中删除美元符号 ($) 和所有逗号 (,)?避免使用正则表达式会更好吗?
String liveprice = "3,456.78";
采纳答案by Prabhakaran Ramaswamy
do like this
这样做
NumberFormat format = NumberFormat.getCurrencyInstance();
Number number = format.parse("$123,456.78");
System.out.println(number.toString());
output
输出
123456.78
回答by Faraday
Here is more information Oracle JavaDocs:
以下是Oracle JavaDocs 的更多信息:
liveprice = liveprice.replace("X", "");
回答by Vishal Suthar
回答by Masudul
Try,
尝试,
String liveprice = "3,456.78";
String newStr = liveprice.replaceAll("[$,]", "");
replaceAll
uses regex, to avoid regex than try with consecutive replace
method.
replaceAll
使用正则表达式,避免使用正则表达式而不是尝试使用连续replace
方法。
String liveprice = ",23,456.78";
String newStr = liveprice.replace("$", "").replace(",", "");
回答by dbw
Just use Replace
instead
只要使用Replace
替代
String liveprice = "3,456.78";
String output = liveprice.replace("$", "");
output = output .replace(",", "");
回答by OldCurmudgeon
Is a replace really what you need?
您真的需要更换吗?
public void test() {
String s = "3,456.78";
StringBuilder t = new StringBuilder();
for ( int i = 0; i < s.length(); i++ ) {
char ch = s.charAt(i);
if ( Character.isDigit(ch)) {
t.append(ch);
}
}
}
This will work for any decorated number.
这适用于任何装饰数字。
回答by Prateek
Without regex, you can try this:
没有正则表达式,你可以试试这个:
String output = "3,456.78".replace("$", "").replace(",", "");
回答by Rajat Bhatia
Example using Swedish Krona currency
使用瑞典克朗货币的示例
String x="19.823.567,10 kr";
String x="19.823.567,10 kr";
x=x.replace(".","");
x=x.replaceAll("\s+","");
x=x.replace(",", ".");
x=x.replaceAll("[^0-9 , .]", "");
System.out.println(x);
System.out.println(x);
Will give the output ->19823567.10(which can now be used for any computation)
将给出输出 ->19823567.10(现在可用于任何计算)
回答by Bruno Lopes Malafaia
I think that you could use regex. For example:
我认为你可以使用正则表达式。例如:
"19.823.567,10 kr".replace(/\D/g, '')
回答by kapsid
In my case, @Prabhakaran's answer did not work, someone can try this.
就我而言,@Prabhakaran 的回答不起作用,有人可以试试这个。
String salary = employee.getEmpSalary().replaceAll("[^\d.]", "");
Float empSalary = Float.parseFloat(salary);