如何在舍入到2位后打印双倍? [重复]

问题描述 投票:2回答:4

我正在使用EazeGraph库来绘制我的Double

  // in percent
    Double PROTEIN_percent = ((PROTEIN_grams / TOTALCALORIES_numbers) * 100);
    Double FAT_percent = ((FAT_grams / TOTALCALORIES_numbers) * 100);
    Double CARBS_percent = ((CARBS_grams / TOTALCALORIES_numbers) * 100);

问题是它不允许我在没有将.floatValue添加到Double的情况下绘制它

  mPieChart.addPieSlice(new PieModel("CARBS", CARBS_percent.floatValue(), Color.parseColor("#FE6DA8")));
    mPieChart.addPieSlice(new PieModel("PROTEIN", PROTEIN_percent.floatValue(), Color.parseColor("#56B7F1")));
    mPieChart.addPieSlice(new PieModel("FAT", FAT_percent.floatValue(), Color.parseColor("#FED70E")));
    mPieChart.startAnimation();

此外,我希望输出舍入为2位数,它不允许我使用String.format("%.2f",因为它不是一个字符串。

这就是我得到的:62.1232131342

这就是我想要的:62.12

java android double
4个回答
0
投票

您有两种选择:

第一选项:禁用小数

这个选项实际上不是一个解决方案,因为从我在他们的库中看到的,你只能在饼图上设置一个自定义的内部值,这将我们带到第二个选项:

mPieChart.setShowDecimal(false);

第二个选项:设置一个监听器来手动更改饼图的内部值。

public static String formatTwoDecimal(double d) {
   NumberFormat numberFormat = new DecimalFormat("#,##0.00");

   return numberFormat.format(d);
}

=======

mPieChart.setUseCustomInnerValue(true); //to override the inner value
mPieChart.setOnItemFocusChangedListener(new IOnItemFocusChangedListener() {
   @Override
   void onItemFocusChanged(int _Position) {
      //_Position is the position of the pie you inserted, in your case, 0 will be the CARBS, 1 is PROTEIN, 2 is FAT
      if (_Position == 0) {
         mPieChart.setInnerValueString(formatTwoDecimal(CARBS_percent));
      } else if (_Position == 1) {
         mPieChart.setInnerValueString(formatTwoDecimal(PROTEIN_percent));
      } else if (_Position == 2) {
         mPieChart.setInnerValueString(formatTwoDecimal(FAT_percent));
      }
   }
});

我实际上没有尝试这个,但根据我对他们的库的评论,这将工作。如果您发现此方法有任何错误,请告诉我。


1
投票

它应该工作。

String twoDecimalResult = String.format("%.2f", CARBS_percent);

0
投票

你可以这样做

Float.parseFloat(String.format("%.2f", 62.1232131342));

0
投票

试试这个

DecimalFormat decimalFormat = new DecimalFormat("#0.00");

decimalFormat.format(Double.parseDouble(" your value "))
© www.soinside.com 2019 - 2024. All rights reserved.