Andrews B Anthony
Andrews B Anthony

Reputation: 1381

Currency Symbol given by DecimalFormat looks invalid

I face the below problem in java 8

import java.util.*;
import java.text.*;
import java.lang.*;

class NumberTest5 {
    public static void main(String[] args) {
        Locale loc = new Locale("sr","ME");
        DecimalFormat df = (DecimalFormat)NumberFormat.getCurrencyInstance(loc);
        System.out.println("\n"+"currencySymbol:"+df.getPositivePrefix()+"\tlength:"+df.getPositivePrefix().length());
        //here the above result is currencySymbol:  €+(non breakable space char)
        //length:2     
    }
}

the real question is why there is an extra character appended to the currency symbol ..?

why the above program behaves in this way ...?.

what is the problem in it & how to rectify it ..?

Thanks

Upvotes: 5

Views: 320

Answers (2)

Lenny
Lenny

Reputation: 33

The getPositivePrefix() method will return a string with the currency symbol and a space character--They do this in order to have the currency symbol and the value separated.

You do not want the space character? You can do two things:


Solution 1

String symbol = df.getDecimalFormatSymbols().getCurrencySymbol();
    System.out.println("\n"+"currencySymbol:"+ symbol + "500\tlength:"+symbol.length());

Output:

currencySymbol:€500 length:1

Solution 2

Add a backspace escape sequence: '\b', this will delete the space during print. But the string length size will remain when calling the length() method

String symbol = df.getPositivePrefix();
    System.out.println("\n"+"currencySymbol:" + symbol +"\b500\tlength:"+symbol.length());

Output:

currencySymbol:€500 length:2

Upvotes: 0

Sotirios Delimanolis
Sotirios Delimanolis

Reputation: 279920

It's not invalid.

The following

Locale loc = new Locale("sr","ME");

represents the Locale for Serbian in Montenegro. I can't find the equivalent for Java, but here's a description of this locale for glibc. Under Currency, you'll notice Space separation between symbol and value is set to 1, indicating that

a space separates the symbol from the value

Therefore, if you formatted a value, for example

System.out.println(df.format(123.45));

you'd get

€ 123,45

with a space between the currency symbol at the value.

That's what the positive previx represents.

Upvotes: 6

Related Questions