向上舍入浮动 .25
Round up float .25
您好,我应该将我的浮点值四舍五入为连续的 .25 值。
示例:
0.123 => 0.25
0.27 => 0.5
0.23 => 0.25
0.78 => 1
0.73 => 0.75
10.20 => 10.25
10.28 => 10.5
我尝试使用 Math.round(myFloat*4)/4f;
但它 return 最近,所以如果我有:
1.1 return 1 and not 1.25
您应该使用 Math.ceil()
而不是 Math.round():
Math.ceil(myFloat*4) / 4.0d;
密切相关:
你几乎成功了。要四舍五入,请使用 Math.ceil(myFloat*4)/4f
而不是 Math.round
您需要实现自己的舍入逻辑。
public static double roundOffValue(double value) {
double d = (double) Math.round(value * 10) / 10;
double iPart = (long) d;
double fPart = value - iPart;
if (value == 0.0) {
return 0;
}else if(fPart == 0.0){
return iPart;
}else if (fPart <= 0.25) {
iPart = iPart + 0.25;
} else if (fPart <= 0.5) {
iPart = iPart + 0.5;
} else if (fPart < 0.75) {
iPart = iPart + 0.75;
} else {
iPart = iPart + 1;
}
return iPart;
}
您好,我应该将我的浮点值四舍五入为连续的 .25 值。 示例:
0.123 => 0.25
0.27 => 0.5
0.23 => 0.25
0.78 => 1
0.73 => 0.75
10.20 => 10.25
10.28 => 10.5
我尝试使用 Math.round(myFloat*4)/4f;
但它 return 最近,所以如果我有:
1.1 return 1 and not 1.25
您应该使用 Math.ceil()
而不是 Math.round():
Math.ceil(myFloat*4) / 4.0d;
密切相关:
你几乎成功了。要四舍五入,请使用 Math.ceil(myFloat*4)/4f
而不是 Math.round
您需要实现自己的舍入逻辑。
public static double roundOffValue(double value) {
double d = (double) Math.round(value * 10) / 10;
double iPart = (long) d;
double fPart = value - iPart;
if (value == 0.0) {
return 0;
}else if(fPart == 0.0){
return iPart;
}else if (fPart <= 0.25) {
iPart = iPart + 0.25;
} else if (fPart <= 0.5) {
iPart = iPart + 0.5;
} else if (fPart < 0.75) {
iPart = iPart + 0.75;
} else {
iPart = iPart + 1;
}
return iPart;
}