2016-05-04 57 views
1

我试图回馈社区多一点...打印正确的小数位数? (printf) - JAVA

让我们说,我的双变量,有时有不同数量的小数位。 (例如1.2,1.23,1.234)但我只想输出变量所具有的最小小数位数,最后没有所有这些0。我怎么做?

+2

“double x = 2.10”有什么问题?的System.out.println(X);'? –

+0

或者如果使用'printf()',则使用'%s'而不是'%f'。 – Andreas

+0

我已经拥有了'System.out.printf();'中的所有东西,所以我想保持它的样子。 :P @ElliottFrisch Plus,这应该有更多的用处,比如将一个字符串绘制到JFrame中,当追加文本时你不能格式化。 – Kaelinator

回答

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... 
} 
+0

您将无法成功完成上述任务。例如,对于x = 0.1502,输出应该是多少?对于x = 0.15002?为.01500002?为0.15000000000000002?你如何从x = .05 + .05 + .05中区分出你想要的,因为它们的内部表示是相同的? – FredK

0

你有双只使用? BigDecimal可以与缩放比例一起使用,以便它只显示所需的小数位数。