DecimalFormat(“#0.000”)没有像1.321那样格式化正确的方式

时间:2013-12-13 07:29:17

标签: android numberformatexception decimalformat

我希望获得一个包含3个小数位的Double我这样做:

String sAveragePrice;

Double dAveragePrice = holePrice/(allPrices.size());    // delivers 1.3210004       
DecimalFormat threeZeroes = new DecimalFormat("#0.000");
sAveragePrice = threeZeroes.format(dAveragePrice);          // delivers then 1,321

格式化之后我得不到1.321而是1,321。然后1,321抛出一个NumberformatException这是抛出的时间:

Double priceInt = Double.parseDouble(sAveragePrice);  // throws NumberFormatException

奇怪的是,我有这个代码直到3周,它没有任何问题。但是今天当我再次启动我的应用程序时,它会遇到问题。但我没有改变任何事情。

任何人都可以帮助我吗? 我也试过了:

NumberFormat format = NumberFormat.getNumberInstance();
format.setMinimumFractionDigits(3);
format.setMaximumFractionDigits(3);
sAveragePrice = format.format(dAveragePrice);

但它也给我一个“,”而不是“。”为了双倍。

4 个答案:

答案 0 :(得分:0)

尝试使用您的数字格式的区域设置。

Number format = NumberFormat.getNumberInstance(Locale.ITALIAN);

Java SDK具有有限数量的预定义语言环境设置,因此对于其他语言环境(例如,对于俄语),您可以使用以下代码段:

Number format = NumberFormat.getNumberInstance(new Locale("ru", "RU"));
Number format = NumberFormat.getNumberInstance(new Locale("it", "IT")); // etc... 

答案 1 :(得分:0)

此示例代码可以帮助您......

    Locale locale = Locale.getDefault();
    // set Locale.US as default
    Locale.setDefault(Locale.US);
    DecimalFormat decimalFormat = new DecimalFormat("##.000");
    double d = 14.5589634d;
    String format = decimalFormat.format(d);
    System.out.println(format);// prints 14.559
    // back to default locale
    Locale.setDefault(locale);

答案 2 :(得分:0)

看看这个问题

How to change the decimal separator of DecimalFormat from comma to dot/point?

基本上你的输出将是Locale特定的,所以如果你有一个Frame of Frame,那么它将与美国的Locale不同。

NumberFormat format = NumberFormat.getNumberInstance(Locale.US);

答案 3 :(得分:0)

使用此类格式 使用#而不是0.这是声明模式的正确格式

String sAveragePrice;

Double dAveragePrice = holePrice/(allPrices.size());       
DecimalFormat threeZeroes = new DecimalFormat("#.###");
sAveragePrice = threeZeroes.format(dAveragePrice);   

希望它能帮到你