>  기사  >  Java  >  BigDecimal이 크기를 비교하는 방법

BigDecimal이 크기를 비교하는 방법

DDD
DDD원래의
2023-12-06 13:44:584387검색

크기 비교 방법: 1. "compareTo()" 메서드를 사용합니다. 2. "equals()" 메서드를 사용합니다. 3. "compareTo()" 메서드의 오버로드된 버전을 사용합니다. ()" 메소드 체인 호출 등

BigDecimal은 고정밀 부동 소수점 연산을 처리하는 데 사용되는 Java 클래스입니다. 비교할 때 BigDecimal은 두 개체의 크기를 비교하는 방법을 제공합니다. 다음은 BigDecimal 개체의 크기를 비교하는 여러 가지 방법입니다.

1. CompareTo() 메서드를 사용합니다.

compareTo() 메서드는 두 BigDecimal 개체 간의 크기 관계를 나타내는 정수 값을 반환합니다. 반환 값이 음수이면 첫 번째 개체가 두 번째 개체보다 작음을 의미하고, 반환 값이 0이면 두 개체가 동일하다는 의미입니다. 반환 값이 양수이면 첫 번째 개체가 두 번째 개체보다 크다는 의미입니다. .

샘플 코드:

import java.math.BigDecimal;  
  
public class BigDecimalComparison {  
    public static void main(String[] args) {  
        BigDecimal number1 = new BigDecimal("10.5");  
        BigDecimal number2 = new BigDecimal("20.5");  
          
        int result = number1.compareTo(number2);  
          
        if (result < 0) {  
            System.out.println("number1 < number2");  
        } else if (result > 0) {  
            System.out.println("number1 > number2");  
        } else {  
            System.out.println("number1 = number2");  
        }  
    }  
}

출력 결과:

number1 < number2

2. equals() 메서드 사용:

equals() 메서드는 두 BigDecimal 객체가 동일한지 비교하는 데 사용됩니다. 두 객체의 수치와 스케일(소수점 이하 자릿수)이 같은지 비교합니다. 같으면 true를 반환하고, 그렇지 않으면 false를 반환합니다.

샘플 코드:

import java.math.BigDecimal;  
  
public class BigDecimalComparison {  
    public static void main(String[] args) {  
        BigDecimal number1 = new BigDecimal("10.5");  
        BigDecimal number2 = new BigDecimal("10.50");  
          
        boolean isEqual = number1.equals(number2);  
          
        if (isEqual) {  
            System.out.println("number1 = number2");  
        } else {  
            System.out.println("number1 != number2");  
        }  
    }  
}

출력 결과:

number1 != number2

참고: equals() 메서드를 사용하여 BigDecimal 객체를 비교할 때 소수점 이하 자릿수인 scale 매개 변수가 고려됩니다. 따라서 비교할 때 눈금 설정에 주의해야 합니다.

3. CompareTo() 메서드의 오버로드 버전 사용:

compareTo() 메서드에는 두 BigDecimal 객체의 상대적 크기를 지정된 객체와 비교하는 데 사용할 수 있는 오버로드 버전도 있습니다. 이 오버로드된 버전의 반환 값은 CompareTo() 메서드의 반환 값과 동일합니다. 이 방법을 통해 두 객체와 특정 객체 사이의 크기 관계를 비교할 수 있습니다.

샘플 코드:

import java.math.BigDecimal;  
  
public class BigDecimalComparison {  
    public static void main(String[] args) {  
        BigDecimal number1 = new BigDecimal("10.5");  
        BigDecimal number2 = new BigDecimal("20.5");  
        BigDecimal number3 = new BigDecimal("15.5");  
          
        int result = number1.compareTo(number2).compareTo(number3);  
          
        if (result < 0) {  
            System.out.println("number1 < number2 < number3");  
        } else if (result == 0) {  
            System.out.println("number1 = number2 = number3");  
        } else {  
            System.out.println("number1 > number2 > number3");  
        }  
    }  
}

이 예에서는 먼저 숫자 1과 숫자 2 사이의 크기 관계를 비교한 다음 결과를 CompareTo() 메서드에 전달한 다음 결과와 숫자 3 사이의 크기 관계를 비교합니다. 최종 결과는 음수이며, 이는 number1이 number2보다 작고, number2가 number3보다 크다는 것을 의미하므로 "number1number3"이 출력될 수 있습니다.

4. CompareTo() 메서드의 연결 호출 사용:

compareTo() 메서드를 연결하여 한 번의 작업으로 여러 비교를 수행할 수도 있습니다. 연쇄 호출을 통해 두 개체와 여러 개체 간의 크기 관계를 비교할 수 있습니다.

샘플 코드:

import java.math.BigDecimal;  
  
public class BigDecimalComparison {  
    public static void main(String[] args) {  
        BigDecimal number1 = new BigDecimal("10.5");  
        BigDecimal number2 = new BigDecimal("20.5");  
        BigDecimal number3 = new BigDecimal("15.5");  
          
        int result = number1.compareTo(number2).compareTo(number3);  
          
        if (result < 0) {  
            System.out.println("number1 < number2 < number3");  
        } else if (result == 0) {  
            System.out.println("number1 = number2 = number3");  
        } else {  
            System.out.println("number1 > number2 > number3");  
        }  
    }  
}

출력 결과:

number1 < number2 > number3

이 예에서는 체인 호출을 사용하여 세 개체의 크기 관계를 비교합니다. 먼저 1번과 2번을 비교하고, 2번과 3번을 비교하여 최종적으로 완전한 비교 결과를 얻습니다.

간단히 말하면 BigDecimal 클래스는 크기를 비교하는 다양한 방법을 제공하여 특정 요구 사항에 따라 다양한 상황을 처리하는 데 적합한 방법을 선택할 수 있습니다.

위 내용은 BigDecimal이 크기를 비교하는 방법의 상세 내용입니다. 자세한 내용은 PHP 중국어 웹사이트의 기타 관련 기사를 참조하세요!

성명:
본 글의 내용은 네티즌들의 자발적인 기여로 작성되었으며, 저작권은 원저작자에게 있습니다. 본 사이트는 이에 상응하는 법적 책임을 지지 않습니다. 표절이나 침해가 의심되는 콘텐츠를 발견한 경우 admin@php.cn으로 문의하세요.