set double format with 2 decimal places [duplicate]

霸气de小男生 提交于 2019-12-18 07:04:06

问题


I have a short equation:

double compute,computed2;

compute=getminutes/60;

where getminutes is int and I want to set the equivalent of compute with 2 decimal places. 0.00 how can I format the equivalent with 2 decimal places?

Example:

compute=45/60 it should be 0.75 

Here is my work:

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);

the out put will be just like :

1.00
7.00 

回答1:


Cast it to Double

compute=(Double)getminutes/60;

and then use DecimalFormat as mentioned by Peter.




回答2:


Just format the output the right way:

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


来源:https://stackoverflow.com/questions/17082115/set-double-format-with-2-decimal-places

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!