在Java中打印带有2个小数位的整数
在我的代码中,我使用整数乘以100作为小数(0.1是10等)。 你能帮我格式化输出以显示为十进制吗?
int x = 100; DecimalFormat df = new DecimalFormat("#.00"); // Set your desired format here. System.out.println(df.format(x/100.0));
我会说使用0.00
作为格式:
int myNumber = 10; DecimalFormat format = new DecimalFormat("0.00"); System.out.println(format.format(myNumber));
它将打印如下:
10.00
这里的优点是:
如果你喜欢:
double myNumber = .1; DecimalFormat format = new DecimalFormat("0.00"); System.out.println(format.format(myNumber));
它将打印如下:
0.10
您可以通过除以它们的因子(作为一个双精度数)打印出一个编码为整数的十进制数
int i = 10; // represents 0.10 System.out.println(i / 100.0);
版画
0.1
如果您需要始终显示两个小数位,您可以使用
System.out.printf("%.2f", i / 100.0);
你可以试试这个: –
new DecimalFormat("0.00######");
要么
NumberFormat f = NumberFormat.getNumberInstance(); f.setMinimumFractionDigits(2);
你可以使用int的double instate。 它为您提供带小数的输出。 然后你可以除以100。
你可以使用int的double instate。 它为您提供带小数的输出。
如果你想要数字站在点后面。 你可以用这个:
**int number=100; double result; result=number/(number.length-1);**
我希望你能用到这个。
根据另一个答案 ,使用BigDecimal
,这也有效:
BigDecimal v = BigDecimal.valueOf(10,2); System.out.println(v.toString()); System.out.println(v.toPlainString()); System.out.println(String.format("%.2f", v)); System.out.printf("%.2f\n",v);
甚至DecimalFormat
旧DecimalFormat
也适用于BigDecimal
:
DecimalFormat df = new DecimalFormat("0.00"); System.out.println(df.format(v));