【发布时间】:2012-10-11 00:35:08
【问题描述】:
在我的代码中,我使用整数乘以 100 作为小数(0.1 是 10 等)。你能帮我格式化输出以显示为十进制吗?
【问题讨论】:
标签: java format number-formatting output
在我的代码中,我使用整数乘以 100 作为小数(0.1 是 10 等)。你能帮我格式化输出以显示为十进制吗?
【问题讨论】:
标签: java format number-formatting output
int x = 100;
DecimalFormat df = new DecimalFormat("#.00"); // Set your desired format here.
System.out.println(df.format(x/100.0));
【讨论】:
100 的有效格式,它应该按照 OP 的预期打印 1.00,而它打印 100.00。使用这个没有意义。
OP 的含义吗,因为我不明白它代表什么? :)
我会说使用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);
【讨论】:
基于another answer,使用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 也可以与 BigDecimal 一起使用:
DecimalFormat df = new DecimalFormat("0.00");
System.out.println(df.format(v));
【讨论】:
你可以试试这个:-
new DecimalFormat("0.00######");
或
NumberFormat f = NumberFormat.getNumberInstance();
f.setMinimumFractionDigits(2);
【讨论】:
你可以使用int的双重instate。 它为您提供带小数的输出。 然后你可以除以 100。
【讨论】:
你可以使用int的双重instate。 它为您提供带小数的输出。
如果您希望数字位于点后面。你可以用这个:
**int number=100;
double result;
result=number/(number.length-1);**
希望你能用这个。
【讨论】: