때로는 가장 가까운 쿼터로 플로트를 반올림해야하며 때로는 가장 가까운 반으로 플로트해야합니다. 내가플로트를 가장 가까운 쿼터로 반올림하는 방법
Math.round(myFloat*4)/4f
를 사용할 수있는 반
Math.round(myFloat*2)/2f
를 사용합니다.
하지만 다른 제안 사항이 있습니까?
때로는 가장 가까운 쿼터로 플로트를 반올림해야하며 때로는 가장 가까운 반으로 플로트해야합니다. 내가플로트를 가장 가까운 쿼터로 반올림하는 방법
Math.round(myFloat*4)/4f
를 사용할 수있는 반
Math.round(myFloat*2)/2f
를 사용합니다.
하지만 다른 제안 사항이 있습니까?
당신이 필요하다 : 반도 두 분기입니다
Math.round(myFloat*4)/4f
때문에이 단일 방정식이뿐만 아니라 반 라운딩 처리됩니다. 반 또는 반올림을 위해 두 개의 다른 방정식을 수행 할 필요는 없습니다.
코드 샘플 :
public class Main {
public static void main(String[] args) {
float coeff = 4f;
System.out.println(Math.round(1.10*coeff)/coeff);
System.out.println(Math.round(1.20*coeff)/coeff);
System.out.println(Math.round(1.33*coeff)/coeff);
System.out.println(Math.round(1.44*coeff)/coeff);
System.out.println(Math.round(1.55*coeff)/coeff);
System.out.println(Math.round(1.66*coeff)/coeff);
System.out.println(Math.round(1.75*coeff)/coeff);
System.out.println(Math.round(1.77*coeff)/coeff);
System.out.println(Math.round(1.88*coeff)/coeff);
System.out.println(Math.round(1.99*coeff)/coeff);
}
}
출력 :
1.0
1.25
1.25
1.5
1.5
1.75
1.75
1.75
2.0
2.0
는 어떻게 모두를 해결할 것인가? 어떤 것을 사용할 지 어떻게 알 수 있습니까? 'Math.round (3.8 * 4)/4f == 3.75' –
@user unk : '반은 2/4'이고 http://download.oracle.com/javase/1.4.2/docs/api/이기 때문에 java/lang/Math.html # round (float)/ –
그러나'Math.round (3.8 * 2)/2f == 4.0'이 아니라 '3.75'입니다. –
수학적으로 말하기, 당신은 그것을 라운드, 0.25하여 플로트를 곱하면, 다음 0.25로 다시 나눌 수있다.
편집 : 죄송합니다. 분기 별 의미를 오해 한 것 같습니다. 그러나, 내가 아는 한, 이것은 다양한 소수 자리와 각도로 반올림하는 가장 간단한 방법입니다.
"4로 곱하면"이라고 생각합니다. – DJClayworth
(Math.round(num/toNearest))*toNearest;
문제가 표시되지 않습니다 toNearest
I에 숫자를 반올림 것입니다 ... – dagnelies