打印正确的小数位数? (printf) - JAVA

时间:2016-05-04 17:15:23

标签: java printing format

我试图回馈社区......

让我们说x,我的双变量,有时会有不同的小数位数。 (例如,1.2,1.23,1.234)但我只想打印变量所具有的最小小数位数,而不是最后的所有0。我该怎么做?

2 个答案:

答案 0 :(得分:0)

这是我想出的(它太简单了,不需要信用):

public static void main(String[] args) {

  double x = 100.512f;

  //no decimal places
  if (x % 1 == 0) {
    System.out.printf("x = %.0f", (float) x);
    //one decimal place
  } else if ((x * 10) % 1 == 0) {
    System.out.printf("x = %.1f", (float) x);
    //two decimal places
  } else if ((x * 100) % 1 == 0) {
    System.out.printf("x = %.2f", (float) x);
    //three decimal places
  } else if ((x * 1000) % 1 == 0) {
    System.out.printf("x = %.3f", (float) x);
  }
  //and so on...
}

答案 1 :(得分:0)

你必须只使用双人吗? BigDecimal可以与比例设置一起使用,以便它只显示所需的小数位数。

相关问题