IT

double을 반올림하여 int로 변환 (Java)

lottoking 2020. 8. 7. 07:49
반응형

double을 반올림하여 int로 변환 (Java)


지금 나는 시도하고 있습니다.

int a = round(n);

여기서 nA는 double그것을 사용하지만 작동하지 않습니다. 내가 뭘 잘못하고 있죠?


round()스 니펫 에서 메소드 의 반환 유형은 무엇입니까?

이것이 Math.round()메소드 인 경우 입력 된 변수가 Double 일 때 Long을 리턴합니다.

따라서 반환 값을 캐스팅해야합니다.

int a = (int) Math.round(doubleVar);

Math.round ()가 마음에 들지 이름 다음과 같은 간단한 방법을 사용할 수도 있습니다.

int a = (int) (doubleVar + 0.5);

다음 과 같이 double 을 "가장 가까운" 정수로 반올림 합니다.

1.4- > 1

1.6- > 2

-2.1- > -2

-1.3- > -1

-1.5- > -2

private int round(double d){
    double dAbs = Math.abs(d);
    int i = (int) dAbs;
    double result = dAbs - (double) i;
    if(result<0.5){
        return d<0 ? -i : i;            
    }else{
        return d<0 ? -(i+1) : i+1;          
    }
}

원하는대로 조건 (결과 <0.5)사용 가능 합니다.


import java.math.*;
public class TestRound11 {
  public static void main(String args[]){
    double d = 3.1537;
    BigDecimal bd = new BigDecimal(d);
    bd = bd.setScale(2,BigDecimal.ROUND_HALF_UP);
    // output is 3.15
    System.out.println(d + " : " + round(d, 2));
    // output is 3.154
    System.out.println(d + " : " + round(d, 3));
  }

  public static double round(double d, int decimalPlace){
    // see the Javadoc about why we use a String in the constructor
    // http://java.sun.com/j2se/1.5.0/docs/api/java/math/BigDecimal.html#BigDecimal(double)
    BigDecimal bd = new BigDecimal(Double.toString(d));
    bd = bd.setScale(decimalPlace,BigDecimal.ROUND_HALF_UP);
    return bd.doubleValue();
  }
}

Math.round 함수가 오버로드되었습니다. float 값을 공용면 int를 제공합니다. 예를 들어 작동합니다.

int a=Math.round(1.7f);

double 값을 대신면 long 값을 제공해야합니다.

int a=(int)Math.round(1.7);

이것은 성능 강화를 방지하기 위해 수행됩니다. double 값은 64 비트이지만 int 변수는 32 비트 만 사용하므로 long (64 비트)으로 변환하지만, 위에서대로 32 비트로 형변환 할 수 있습니다.


의 문서 Math.round:

인수를 정수 로 반올림 한 결과를 반환합니다 . 결과는 (int) Math.floor(f+0.5).

에 캐스트 할 필요가 없습니다 int. 과거와 달라졌을 수도 있습니다.


public static int round(double d) {
    if (d > 0) {
        return (int) (d + 0.5);
    } else {
        return (int) (d - 0.5);
    }
}

더 완전한 예제를 게시해야하므로 수행하려는 작업을 확인할 수 있습니다. 귀하가 게시 한 내용에서 볼 수있는 내용은 다음과 같습니다. 첫째, 기본 제공 round()방법 이 없습니다 . 을 호출 Math.round(n)하거나 정적으로 가져와야합니다 Math.round. 그런 다음 원하는대로 호출해야합니다.

참고 URL : https://stackoverflow.com/questions/2654839/rounding-a-double-to-turn-it-into-an-int-java

반응형