【问题标题】:set double format with 2 decimal places [duplicate]设置带 2 个小数位的双格式 [重复]
【发布时间】:2013-06-09 13:06:34
【问题描述】:

我有一个简短的方程式:

double compute,computed2;

compute=getminutes/60;

其中getminutesint,我想将compute 的等效项设置为小数点后两位。 0.00我怎样才能格式化带有 2 位小数的等价物?

例子:

compute=45/60 it should be 0.75 

这是我的作品:

DecimalFormat df2 = new DecimalFormat("00.00000");
double computed,computed2 = 00.000;

computed=60/getitbyminutes;
df2.format(computed);
computed2=computed-8;
df2.format(computed2);

System.out.printf("%1$.2f",computed);
System.out.println();
System.out.printf("%1$.2f",computed2);

输出将是这样的:

1.00
7.00 

【问题讨论】:

  • "compute=45/60 它应该是 0.75" 不在 Java 中。试试 45.0d/60.0d

标签: java swing int decimal decimalformat


【解决方案1】:

只需以正确的方式格式化输出:

double d = 1.234567;
DecimalFormat df = new DecimalFormat("#.##");
System.out.print(df.format(d));

【讨论】:

  • compute=45/60 它应该是 0.75。我的双精度没有声明...它是一个整数。
【解决方案2】:

将其转换为 Double

compute=(Double)getminutes/60;

然后使用 Peter 提到的DecimalFormat

【讨论】:

  • 是的!谢谢这解决了我的问题。为什么我不能接受你的回答?
  • @JonSnow:很高兴我能帮上忙!您收到什么错误消息?
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2011-04-27
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-05-21
  • 2013-08-27
  • 2015-08-22
相关资源
最近更新 更多