Reputation: 89
I'm trying to do currency formatting in my text editor. I wrote some code and I have a problem. NumberFormat is returning different currency symbols on different devices.
Here's my source code:
final NumberFormat nf = NumberFormat.getInstance(Locale.US);
transfer_maney.addTextChangedListener(new TextWatcher() {
@Override
public void beforeTextChanged(CharSequence s, int start, int count, int after) {
}
@Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
if (!s.toString().equals(current)) {
transfer_maney.removeTextChangedListener(this);
String cleanString = s.toString().replaceAll("[$,.]", "");
double parsed = Double.parseDouble(cleanString);
String formatted = nf.getCurrencyInstance().format((parsed / 100));
current = formatted;
if (formatted.contains("$")) {
formatted = formatted.replace("$", "");
}
transfer_maney.setText(formatted);
transfer_maney.setSelection(formatted.length());
transfer_maney.addTextChangedListener(this);
}
}
@Override
public void afterTextChanged(Editable s) {
}
});
My goal is to always return $
symbol and then remove it. As I said, on different devices I have different symbols. On some devices I get a $
symbol, on some £
symbol. What should I change in my code, so it will always return dollar symbol ($
) so I can remove it?
I tried to change the Locale
but it's not working. If anyone knows solution please help me.
Thanks everyone
Upvotes: 3
Views: 2862
Reputation: 1188
The problem is that you are using a static method NumberFormat.getCurrencyInstance()
that works that way:
public final static NumberFormat getCurrencyInstance() {
return getInstance(Locale.getDefault(Locale.Category.FORMAT), CURRENCYSTYLE);
}
As you can see, it returns a NumberFormat
object with a default Locale
, not the Locale
you are setting. That means it depends on user device settings.
So, instead of calling format
on that statically returned instance with default Locale
:
nf.getCurrencyInstance().format(parsed / 100);
which is effectively the same as:
NumberFormat.getCurrencyInstance().format(parsed / 100);
Use your instance with Locale
that you've set:
final NumberFormat nf = NumberFormat.getInstance(Locale.US);
String formatted = nf.format(parsed / 100);
Upvotes: 1