【问题标题】:Formatting decimal number for any location格式化任何位置的十进制数
【发布时间】:2015-04-18 17:57:34
【问题描述】:

我正在尝试格式化一个十进制数字以显示它以设备所在位置的格式显示。我还希望这个十进制数字四舍五入到最接近的第 10 位,如果是,则不显示第 10 位“.0”。

我想我已经接近了。我目前拥有的是这样的:

NumberFormat numberFormat = NumberFormat.getInstance(getResources().getConfiguration().locale);

if (numberFormat instanceof DecimalFormat) {
    ((DecimalFormat)numberFormat).setDecimalSeparatorAlwaysShown(true);
    ((DecimalFormat)numberFormat).applyPattern("0.#");
}

myText.setText(numberFormat.format(myValue));

但是,如果我的数字大于 1,000 ex: 1000.5TextView 将显示 1000.5 而不是 1,000.5(我在美国)。

谁能给我解释一下为什么?

【问题讨论】:

    标签: android locale number-formatting


    【解决方案1】:

    您应该致电setGrouping(boolean) 以确保已启用分组。

    NumberFormat numberFormat = NumberFormat.getInstance(getResources().getConfiguration().locale);
    
    if (numberFormat instanceof DecimalFormat) {
        final DecimalFormat df = (DecimalFormat)numberFormat;
        df.setDecimalSeparatorAlwaysShown(true);
        df.setGroupingUsed(true);
        df.applyPattern("0.#");
    }
    
    myText.setText(numberFormat.format(myValue));
    

    【讨论】:

    • 感谢您的回复。我按照您的示例进行操作,但 TextView 仍显示“1000.5”。 link
    猜你喜欢
    • 2013-08-22
    • 2020-07-21
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-07-25
    • 1970-01-01
    相关资源
    最近更新 更多