【问题标题】:change format of double like ***.***,**更改双精度格式,如 ***.***,**
【发布时间】:2013-12-18 16:49:36
【问题描述】:

我有double amount。设总量为500000.12。我想将金额的值设置为 TextView 像这种格式 500,000.12 (其中 12 是美分,500,000 是美元)。

我写了这个函数,它可以工作

private String getAmountAsString(double amount) {
        double integralPart = amount % 1;
        int fractionalPart = (int) (amount - integralPart);
        int integral = (int) integralPart * 100;
        String strFractional = String.format("%,d", fractionalPart);
        String strAmount = (strFractional + "." + String.valueOf(integral));

        return strAmount;
    }

但我认为使用 java 原生函数可以有一些简单而好的方法。任何人都可以帮助找到功能或更好的方法吗?

【问题讨论】:

    标签: android double


    【解决方案1】:

    各种Locale可用于格式化float, double等。您可以使用:

    String.format(Locale.<Your Locale>, "%1$,.2f", myDouble);
    

    这里的.2f 表示你想要小数点后的位数。如果您没有指定任何语言环境,它将使用默认语言环境。

    在 String 类中这个方法被重载为:

    format(String format, Object... args)  
    &
    format(Locale l, String format, Object... args)
    

    欲了解更多信息,请查看:Link1Link2Link3

    【讨论】:

    • 非常感谢,这就是我想要的。一行而不是写一些函数。
    • +1 为重点回答。我不知道语言环境。我应该为 Locale 提供什么价值?
    【解决方案2】:

    因此使用NumberFormats。它们可以很好地处理不同国家/地区的本地差异。

    //define a local, gets automated if a point or comma is correct in this Country.
    NumberFormat anotherFormat = NumberFormat.getNumberInstance(Locale.US);
    DecimalFormat anotherDFormat = (DecimalFormat) anotherFormat;
    anotherDFormat.applyPattern("#.00");//set the number of digits afer the point
    anotherDFormat.setGroupingUsed(true);// set grouping
    anotherDFormat.setGroupingSize(3);//and size of grouping
    double myDouble = 123456.78;
    String numberWithSeparators = anotherDFormat.format(myDouble);//convert it
    

    【讨论】:

      【解决方案3】:

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2013-03-17
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2012-11-08
        • 1970-01-01
        相关资源
        最近更新 更多