Decimal point or decimal comma in Android

2020-08-09 07:26发布

Is there an easy way to read back if the language set uses a decimal comma or a decimal point?

5条回答
何必那么认真
2楼-- · 2020-08-09 07:44

Not sure if there is an easy way, but you could test which language set is being used and then make the appropriate changes according to if that language used commas or decimals.

查看更多
虎瘦雄心在
3楼-- · 2020-08-09 07:48

I did try this and it worked fine...

    String osVersion = System.getProperty("os.version");
String PhoneModel = android.os.Build.MODEL;
String locale = this.getResources().getConfiguration().locale.getDisplayCountry();
char decSeparator = '*';
DecimalFormatSymbols dfs = new DecimalFormatSymbols();
decSeparator = dfs.getDecimalSeparator();
String androidVersion = android.os.Build.VERSION.RELEASE;
String prologue = String.format("OS verson = %s PhoneModel = %s locale = %s DecimalFormatSymbol = [%c] androidVersion = %s ", 
        osVersion ,PhoneModel, locale, decSeparator,androidVersion);
查看更多
冷血范
4楼-- · 2020-08-09 07:49

you can use:

Currency currency = Currency.getInstance(device_locale);

than use currency.getSymbol() for symbol. For default device locale you can use:

@TargetApi(Build.VERSION_CODES.N)
    public static Locale getCurrentLocale(Context c) {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
            return c.getResources().getConfiguration().getLocales().get(0);
        } else {
            //noinspection deprecation
            return c.getResources().getConfiguration().locale;
        }
    }
查看更多
叛逆
5楼-- · 2020-08-09 07:55

Or why not

DecimalFormatSymbols.getInstance().decimalSeparator
查看更多
Rolldiameter
6楼-- · 2020-08-09 08:02

EDIT: Updating based on @Algar's suggestion; you can directly use:

char separatorChar = DecimalFormatSymbols.getInstance().getDecimalSeparator();

As it will always return an instance of DecimalFormatSymbols.


NumberFormat nf = NumberFormat.getInstance();
if (nf instanceof DecimalFormat) {
    DecimalFormatSymbols sym = ((DecimalFormat) nf).getDecimalFormatSymbols();
    char decSeparator = sym.getDecimalSeparator();
}

Docs:

NumberFormat, DecimalFormat, DecimalFormatSymbols

According to the DecimalFormat docs, apparently calling NumberFormat.getInstance() is safe, but may return a subclass other than DecimalFormat (the other option I see is ChoiceFormat). I believe for the majority of instances it should be a DecimalFormat, and then you can compare decSeparator against a , and . to see which format it is using.

查看更多
登录 后发表回答