简体   繁体   English

从 Java 中的欧元货币字符串中删除空格

[英]Removing spaces from a EUR currency string in Java

I have a method that convert a number into a currency, for "USD" and "GBP" it's working good, but with "EUR" the NumberFormat it's rendering a string with a space between the symbol and the number € 1.207.987,00 rather then dollar and pound "$1,207,987.00" , "£1,207,987.00" .我有一种将数字转换为货币的方法,对于“USD”和“GBP”来说效果很好,但是对于“EUR”NumberFormat,它会呈现一个字符串,符号和数字之间有一个空格€ 1.207.987,00而不是美元和英镑"$1,207,987.00" , "£1,207,987.00" I tried use replace and replace all to remove this but nothing works for me, follow the code:我尝试使用 replace 和 replace all 来删除它,但对我没有任何作用,请按照以下代码操作:

 public static void main(String[] argsd) {
        Number rawNumber = 120798700;
         NumberFormat numberFormat = NumberFormat.getCurrencyInstance(Locale.forLanguageTag("nl"));
         Currency currency = Currency.getInstance("EUR");
         numberFormat.setCurrency(currency);
         String numberRemoveSpaces = numberFormat.format((rawNumber.floatValue() / 100)).replaceAll("\\s+", "");
        System.out.println(numberRemoveSpaces);
    }

If you want to remove it, try this:如果你想删除它,试试这个:

String numberRemoveSpaces = numberFormat.format((rawNumber.floatValue() / 100)).replaceAll("\\p{Z}","");

That removes any kind of whitespace or invisible separator.这会删除任何类型的空格或不可见的分隔符。

You can use the following, instead of your current replaceAll() :您可以使用以下内容,而不是您当前的replaceAll()

replaceFirst("\\u00A0", "")

The Unicode value of U+00A0 is a non-breaking space (see here ). U+00A0 的 Unicode 值是一个不间断空格(请参阅此处)。 This is the specific character being used to separate the currency symbol from the amount.这是用于将货币符号与金额分开的特定字符。

You can also choose to build a custom format as follows:您还可以选择构建自定义格式,如下所示:

NumberFormat nf = NumberFormat.getCurrencyInstance();
DecimalFormatSymbols dfs = new DecimalFormatSymbols();
dfs.setCurrencySymbol("€");
dfs.setGroupingSeparator('.');
dfs.setMonetaryDecimalSeparator(',');
((DecimalFormat) nf).setDecimalFormatSymbols(dfs);
System.out.println(nf.format(rawNumber.floatValue() / 100));

This also gives the same output:这也给出了相同的输出:

€1.207.987,00

感谢大家的所有答案,但根据http://www.bubblefoundry.com/blog/2013/11/formatting-dutch-currency-amounts/荷兰货币的默认格式在符号和数字之间有空格,所以我将与空间保持一致。

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

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