MarcusSlover
MarcusSlover

Reputation: 88

Why does the NumberFormat returns blank fields?

So a few days ago I encountered a weird problem however, I didn't change any that kind of code. The problem is the format I'm getting from my method which I used for years. All commas are now spaces (blank fields) and I have no idea what is causing this.

public static String toFancyCost(int num) {
    return NumberFormat.getInstance().format((Integer) num);
}

Before even this happened the String I received was looking like for example 2,181,273 and not like 2 181 273.

Upvotes: 0

Views: 91

Answers (3)

Brooklyn99
Brooklyn99

Reputation: 1047

As commented above, somehow the system default may have been modified. Let's stick the code to set the locale when formatting by using below to avoid any issues.

int number = 345678987;

NumberFormat numberFormat = NumberFormat.getNumberInstance(Locale.US);// Locale.US or any other locale you required
String numberAsString = numberFormat.format(number);
System.out.println(numberAsString);

response:

345,678,987

when I use the below for example with Locale.CANADA_FRENCH

 int number = 345678987;
 NumberFormat numberFormat = NumberFormat.getNumberInstance(Locale.CANADA_FRENCH);
 String numberAsString = numberFormat.format(number);
 System.out.println(numberAsString);

response:

345 678 987

So in your case also locale may have been causing issues, so please explictly set locale.

Upvotes: 0

Mark
Mark

Reputation: 5239

You must have changed your system locale by accident. The implementation of NumberFormat.getInstance() (on 1.8.0_131):

public final static NumberFormat getInstance() {
    return getInstance(Locale.getDefault(Locale.Category.FORMAT), NUMBERSTYLE);
}

It uses formatting specified by the default locale. and the java docs on Locale.getDefault say:

The Java Virtual Machine sets the default locale during startup based on the host environment. It is used by many locale-sensitive methods if no locale is explicitly specified. It can be changed using the setDefault method.

If you were to use NumberFormat.getInstance(Locale) you can specify which locale the NumberFormat should use.

Upvotes: 3

alibttb
alibttb

Reputation: 545

Your systems default local is using a space as thousands separator, number format retured by getInstance() uses settings from system's default local.

Upvotes: 0

Related Questions