简体   繁体   中英

NumberFormat.getCurrencyInstance() formats to a string with whitespace, that is no whitespace. How to remove it?

I have the following code:

NumberFormat numberFormat = NumberFormat.getCurrencyInstance(getLocale());
return numberFormat.format("-123.45").replaceAll("\\s", "");

Since the format returns "-€ 123,45" for my locale, I would expect the code to return "-€123,45", but it returns "-€ 123,45". When inspecting the returned string it says that it has a -96 instead of a space. So obviously instead of inserting a space, format inserts that mysterious -96 character. How can I remove that -96 character?

That is character 0xA0, or , or non-breaking space (or NO-BREAK SPACE) in - for example - Windows-1252 and Unicode. This is used to prevent a line break or wrap from occurring after the currency symbol, but before the number.

The regex character class \s in Java only covers:

A whitespace character: [ \t\n\x0B\f\r]

See javadoc of java.util.regex.Pattern .

Instead, use \\h instead of \\s , as \h covers:

A horizontal whitespace character: [ \t\xA0 ᠎ - ]

Or, only replace .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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