Java 检查 BigDecimal 值是否在范围内

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/26996600/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-11 03:37:39  来源:igfitidea点击:

Check if BigDecimal value is in range

javabigdecimal

提问by user3127896

I have BiGDecimal priceand i need to check if it is in some range. For example should be 3 conditions:

我有BiGDecimal price,我需要检查它是否在某个范围内。例如应该是3个条件:

if (price >= 0 and price <=500) {
   ....
} else if (price >=500 && price <=1000) {
   ....
} else if (price > 1000) {
   ....
}

How to do it right using BigDecimal type.

如何正确使用 BigDecimal 类型。

采纳答案by Anders R. Bystrup

That is achievable using the .compareTo()method. For instance:

这可以使用.compareTo()方法实现。例如:

if ( price.compareTo( BigDecimal.valueOf( 500 ) > 0 
     && price.compareTo( BigDecimal.valueOf( 1000 ) < 0 ) {
    // price is larger than 500 and less than 1000
    ...
}

Quoting (and paraphrasing) from the JavaDoc:

从 JavaDoc 引用(和释义):

The suggested idiom for performing these comparisons is: (x.compareTo(y) op0), where opis one of the six comparison operators [(<, ==, >, >=, !=, <=)]

执行这些比较的建议习惯用法是:(x.compareTo(y) op0),其中op是六个比较运算符之一[(<, ==, >, >=, !=, <=)]

Cheers,

干杯,

回答by Simulant

Use BigDecimal.compareTo(val)to compare if your Number is bigger, smaller or equal.

使用BigDecimal.compareTo(val)比较,如果你的号码是更大,更小或相等。

returns -1, 0, or 1 as this BigDecimal is numerically less than, equal to, or greater than val.

返回 -1、0 或 1,因为此 BigDecimal 在数字上小于、等于或大于 val。

if (price.compareTo(BigDecimal.ZERO) >= 0 && 
    price.compareTo(new BigDecimal(500)) <= 0) {
   ....
}  else if (price.compareTo(new BigDecimal(500)) >= 0 && 
            price.compareTo(new BigDecimal(1000)) <= 0) {
   ....
} else if (price.compareTo(price.compareTo(new BigDecimal(1000)) < 0) {
   ....
}

回答by Prabhu R.D

use compareTo method

使用 compareTo 方法

java.math.BigDecimal.compareTo(BigDecimal val)

java.math.BigDecimal.compareTo(BigDecimal val)

This method returns -1 if the BigDecimal is less than val, 1 if the BigDecimal is greater than val and 0 if the BigDecimal is equal to val

如果 BigDecimal 小于 val,则此方法返回 -1;如果 BigDecimal 大于 val,则返回 1;如果 BigDecimal 等于 val,则返回 0

回答by Beri

There is no workaround to this i think. Eventually you could wrap it into a nice design pattern, but BigDecimal has only one method for comparing.

我认为没有解决方法。最终,您可以将其包装成一个不错的设计模式,但 BigDecimal 只有一种比较方法。

My idea is to extract a method for range:

我的想法是提取范围的方法:

boolean isBetween(BigDecimal price, BigDecimal start, BigDecimal end){
  return price.compareTo(start) > 0 && price.compareTo(end) < 0;
}

回答by Semih Eker

You can do sthg like this;

你可以这样做;

public class BigDecimalDemo {

  public static void main(String[] args) {

    // create 2 BigDecimal objects
    BigDecimal bg1, bg2;

    bg1 = new BigDecimal("10");
    bg2 = new BigDecimal("20");

    //create int object
    int res;

    res = bg1.compareTo(bg2); // compare bg1 with bg2

    String str1 = "Both values are equal ";
    String str2 = "First Value is greater ";
    String str3 = "Second value is greater";

    if( res == 0 )
      System.out.println( str1 );
   else if( res == 1 )
      System.out.println( str2 );
   else if( res == -1 )
     System.out.println( str3 );
 }
}

resource : http://www.tutorialspoint.com/java/math/bigdecimal_compareto.htm

资源:http: //www.tutorialspoint.com/java/math/bigdecimal_compareto.htm

回答by dani77

Use signum method from BigDecimal class:

使用 BigDecimal 类中的 signum 方法:

private static boolean isBetween(BigDecimal amount, BigDecimal init, BigDecimal end) {
    return amount.subtract(init).signum() >= 0 && amount.subtract(end).signum() <= 0;
}

回答by Kirill Karandin

Lets make it generic:

让我们让它通用:

public static <T extends Comparable<T>> boolean isBetween(T value, T start, T end) {
    return value.compareTo(start) >= 0 && value.compareTo(end) <= 0;
}

回答by Luigi Scognamiglio

As said by Kirill Karandin, you can write a generic method:

正如 Kirill Karandin 所说,您可以编写一个泛型方法:

public static <T extends Comparable<T>> boolean isBetween(T x, T lowerBound, T upperBound) {
    return (x.compareTo(lowerBound) + upperBound.compareTo(x)) > 0;
}

The difference is that the inner sum will return:

不同之处在于内部总和将返回:

  • 0, if x is either less than of min or greater than of max;
  • 1, if x is equal to either min or max;
  • 2, if x belong to the interval, but it's not equal to either min or max.
  • 0,如果 x 小于 min 或大于 max;
  • 1,如果 x 等于 min 或 max;
  • 2、如果x属于区间,但既不等于min也不等于max。

Consequently, if the sum is greater than of 0 (or simply not equal to 0) the x variable will belong to the interval.

因此,如果总和大于 0(或简单地不等于 0),则 x 变量将属于该区间。

回答by beat

If you already use Apache commons lang, one option is to use the Rangeclass instead of writing your own utility method:

如果您已经使用 Apache commons lang,一种选择是使用Range类而不是编写您自己的实用程序方法:

@Test
public void bigDecimalInRange() {
  Range<BigDecimal> myRange = Range.between(BigDecimal.TEN, BigDecimal.valueOf(300));
  BigDecimal tooSmallAmount = new BigDecimal("2.50");
  assertFalse(myRange.contains(tooSmallAmount));

  BigDecimal rightAmount = new BigDecimal("10.01");
  assertTrue(myRange.contains(rightAmount));
}

回答by Johan Sebastian Navarro Cano

BigDecimal value = BigDecimal.valueOf(2);
BigDecimal zero = BigDecimal.valueOf(0);
BigDecimal one = BigDecimal.valueOf(1);
// When it is greater than 0 it returns 1 or if it is equal to 0 it returns 0
System.out.println(value.compareTo(BigDecimal.ZERO)>=0);
// When it is greater than 1 it returns -1 or if it is equal to 1 it returns 0
System.out.println(value.compareTo(BigDecimal.ONE)<=0);
boolean condition =  value.compareTo(BigDecimal.ZERO) >= 0 && value.compareTo(BigDecimal.ONE) <= 0;
System.out.println(condition);