public static double round(double number,int numberofdecimals){
int n=1;
for (int i = 1; i <= numberofdecimals;i++){
n=n*10;
}
double c =((number - Math.floor(number))*n);
c= Math.floor(c);
return (Math.floor(number) + (c/n));
}
我的方法完美地舍入了一些 double ,但是当我将 ((5.0/3) ,2) 放入我的数字参数时,它给了我 1.6600000 发生了什么?
最佳答案
假设您想要进行标准舍入(1.5 舍入到 2.0;1.49 舍入到 1.0),然后尝试以下操作:
public static double round(double number,int numberofdecimals){
int n=1;
for (int i = 1; i <= numberofdecimals;i++){
n=n*10;
}
double c =((number - Math.floor(number))*n); // Here c = 66.6666666...
c= Math.floor(c + 0.5); // Now c is 67.0.
return (Math.floor(number) + (c/n)); // returns 1.67
}
关于java - 我的方法无法舍入1,66666 (5.0/3),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37255280/