嗨,我需要一些四舍五入的帮助,如下所述:
请帮助我。
答案 0 :(得分:0)
由于您要请求特定的行为,因此可以执行以下操作:
public static void main(String[] args){
String res = formatNum(18.9000); //18.89
if(res.indexOf(".") < 0)
System.out.println(Integer.parseInt(res));
else
System.out.println(Double.parseDouble(res));
res = formatNum(18.0000);//18
if(res.indexOf(".") < 0)
System.out.println(Integer.parseInt(res));
else
System.out.println(Double.parseDouble(res));
res = formatNum(18.8689); //18.86
if(res.indexOf(".") < 0)
System.out.println(Integer.parseInt(res));
else
System.out.println(Double.parseDouble(res));
}
private static String formatNum(double num) {
double n1 = Math.floor(num*100)/100;
int n2 = (int)Math.round(num);
return (n1==n2) ? n2+"" : n1+"";
}