我需要显示两个十进制值。在做Double d=(Double) 123400/100
;我的结果为d=1234.0
;我使用了DecimalFormat,结果为d=1234
。我需要结果为d=1234.00
。
Double d = (Double) 123400d / 100;
DecimalFormat df = new DecimalFormat("#.##");
System.out.print("Formatted : " + df.format(d));
答案 0 :(得分:2)
尝试类似:
double d= 123400/100.;
String s = String.format("%.2f", d);
System.out.println(s);
答案 1 :(得分:1)
Double d=(Double) 123400/100;
此语句必须导致编译时错误,指出int不能转换为double。
现在您的问题的解决方案是文本格式化。使用java.text.DecimalFormat;。
import java.text.DecimalFormat;
public class FormatClazz {
public static void main(String[] args) {
Double d = 123400/100 * 1.00;
DecimalFormat df2 = new DecimalFormat("#.00");
System.out.println((df2.format(d)));
}
}
答案 2 :(得分:0)
您可以像这样设置小数位数
setMinimumFractionDigits(2)
E.g。
public class T {
public static void main(String[] args) {
Double d = (Double) 123400.0 / 100;
DecimalFormat df = new DecimalFormat("#.##");
df.setMinimumFractionDigits(2);
System.out.print("Formatted : " + df.format(d));
}
}
输出
Formatted : 1234.00