programing

이중이 정수인지 검사하는 방법

minecode 2022. 8. 11. 21:19
반응형

이중이 정수인지 검사하는 방법

이거 할 수 있어요?

double variable;
variable = 5;
/* the below should return true, since 5 is an int. 
if variable were to equal 5.7, then it would return false. */
if(variable == int) {
    //do stuff
}

암호는 아마 그런식으로 안 될거란건 알지만, 어떻게 되는거야?

또는 modulo 연산자를 사용할 수 있습니다.

(d % 1) == 0

if ((variable == Math.floor(variable)) && !Double.isInfinite(variable)) {
    // integer type
}

그러면 반올림된 더블의 값이 더블과 동일한지 여부를 확인합니다.

할 수 int는 double로 설정할 수 .Math.floor(variable)값이 가 int와 Math.floor(variable)인트라

변수의 값이 무한 또는 음의 무한인 경우에도 이 방법은 작동하지 않습니다. 따라서 조건에 '변수가 무한하지 않은 한'을 추가합니다.

Guava: . (공개:내가 썼어.)또는 Guava를 아직 Import하지 않은 경우,x == Math.rint(x)이라고 생각합니다.rint is보다 상당히 floor ★★★★★★★★★★★★★★★★★」ceil.

public static boolean isInt(double d)
{
    return d == (int) d;
}

이렇게 해봐.

public static boolean isInteger(double number){
    return Math.ceil(number) == Math.floor(number); 
}

예를 들어 다음과 같습니다.

Math.ceil(12.9) = 13; Math.floor(12.9) = 12;

단, 12.9는 정수가 아닙니다.

 Math.ceil(12.0) = 12; Math.floor(12.0) =12; 

따라서 12.0은 정수입니다.

여기 좋은 해결책이 있습니다.

if (variable == (int)variable) {
    //logic
}

고려사항:

Double.isFinite (value) && Double.compare (value, StrictMath.rint (value)) == 0

값('Java') 합니다.==( )이러한 것은 나쁜 것입니다.isFinite() 불가결하다rint()이치노

'이 요.Integer ★★★★★★★★★★★★★★★★★」Double:

    private static boolean isInteger(Double variable) {
    if (    variable.equals(Math.floor(variable)) && 
            !Double.isInfinite(variable)          &&
            !Double.isNaN(variable)               &&
            variable <= Integer.MAX_VALUE         &&
            variable >= Integer.MIN_VALUE) {
        return true;
    } else {
        return false;
    }
}

Double로로 합니다.Integer:

Integer intVariable = variable.intValue();

위의 SkonJeet의 답변과 비슷하지만 성능은 더 우수합니다(적어도 자바에서는).

Double zero = 0d;    
zero.longValue() == zero.doubleValue()
public static boolean isInteger(double d) {
  // Note that Double.NaN is not equal to anything, even itself.
  return (d == Math.floor(d)) && !Double.isInfinite(d);
}

심플한 솔루션:

private boolean checkIfInt(double value){
 return value - Math.floor(value) == 0;
 }

제 해결책은

double variable=the number;
if(variable-(int)variable=0.0){
 // do stuff
   }

다음과 같은 방법으로 시도할 수 있습니다.배수의 정수값을 가져와 원래 배수의 값을 뺀 다음 반올림 범위를 정의하고 새로운 배수의 절대수(정수 부분 제외)가 정의된 범위보다 큰지 작은지 여부를 테스트합니다.이 값이 작으면 정수 값이라고 할 수 있습니다.예:

public final double testRange = 0.2;

public static boolean doubleIsInteger(double d){
    int i = (int)d;
    double abs = Math.abs(d-i);
    return abs <= testRange;
}

d에 값 33.15를 할당하면 메서드는 true를 반환합니다.더 나은 결과를 얻으려면 사용자 재량에 따라 testRange에 더 낮은 값(0.0002)을 할당할 수 있습니다.

개인적으로, 저는 수용된 답변 중 간단한 모듈로 운영 솔루션을 선호합니다.안타깝게도 SonarQube는 원형 정밀도를 설정하지 않은 부동 소수점에서의 동등성 테스트를 좋아하지 않습니다.그래서 좀 더 준거한 솔루션을 찾으려고 노력했습니다.여기 있습니다.

if (new BigDecimal(decimalValue).remainder(new BigDecimal(1)).equals(BigDecimal.ZERO)) {
    // no decimal places
} else {
    // decimal places
}

Remainder(BigDecimal)를 반환하다BigDecimal은 " " " 입니다.(this % divisor)이 값이 0이면 부동 소수점이 없다는 것을 알 수 있습니다.

때문에.%연산자는 BigDecimal 및 int(즉 1)에 직접 적용할 수 없기 때문에 다음 스니펫을 사용하여 BigDecimal이 정수인지 확인합니다.

value.stripTrailingZeros().scale() <= 0

이를 위한 간단한 방법일 수 있습니다.

    double d = 7.88;    //sample example
    int x=floor(d);     //floor of number
    int y=ceil(d);      //ceil of number
    if(x==y)            //both floor and ceil will be same for integer number
        cout<<"integer number";
    else
        cout<<"double number";

Eric Tan의 답변(규모 확인)과 유사합니다(아마도 열등합니다).

double d = 4096.00000;
BigDecimal bd = BigDecimal.valueOf(d);
String s = bd.stripTrailingZeros().toPlainString();
      
boolean isInteger = s.indexOf(".")==-1;

해결책은 다음과 같습니다.

float var = Your_Value;
if ((var - Math.floor(var)) == 0.0f)
{
    // var is an integer, so do stuff
}

언급URL : https://stackoverflow.com/questions/9898512/how-to-test-if-a-double-is-an-integer

반응형