Android中的小数点或小逗号



如果语言集使用小数逗号或小数点,是否有一种简单的方法来读取?

编辑:根据@Algar的建议更新;可以直接使用:

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

因为它总是返回一个DecimalFormatSymbols的实例。


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

文档:

NumberFormat, DecimalFormat, DecimalFormatSymbols

根据DecimalFormat文档,显然调用NumberFormat.getInstance()是安全的,但可能返回一个子类而不是DecimalFormat(我看到的另一个选项是ChoiceFormat)。我相信在大多数情况下,它应该是一个十进制格式,然后你可以比较decSeparator,.,看看它是使用哪种格式。

为什么不

DecimalFormatSymbols.getInstance().decimalSeparator

我确实尝试了这个,它工作得很好…

    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);

可以使用:

Currency currency = Currency.getInstance(device_locale);

使用currency.getSymbol()作为符号。对于默认的设备区域设置,您可以使用:

@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;
        }
    }

不确定是否有简单的方法,但您可以测试正在使用的语言集,然后根据该语言是否使用逗号或小数进行适当的更改。

最新更新