【问题标题】:Groovy numeric String compareGroovy 数字字符串比较
【发布时间】:2013-03-24 04:20:30
【问题描述】:

我做错了什么:

assert  'foo'  == 'foo'  //PASS
assert  '500'  == '500'  //PASS
assert  '500'  <  '1000' //FAIL <-- Supposed to pass
assert  '500'  <= '1000' //FAIL <-- Supposed to pass
assert  '1000' >  '500'  //FAIL <-- Supposed to pass
assert  '1000' >= '500'  //FAIL <-- Supposed to pass

这是一个可定制的“条件”对象:

class Condition {
    static def compareClosure = [
            '==' : { a, b -> a == b},
            '!=' : { a, b -> a != b},
            '<'  : { a, b -> a <  b},
            '<=' : { a, b -> a <= b},
            '>'  : { a, b -> a >  b},
            '>=' : { a, b -> a >= b}
    ]

    String comparator
    def value

    Condition(String comparator, String value) {
        this.value = value
        this.comparator = comparator
    }

    boolean isSatisfiedBy(def value) {
        compareClosure[comparator](value, this.value)
    }
}

所以

assert new Condition('<=', '1000').isSatisfiedBy('500') //FAIL

有没有办法在不将值转换为数字类型的情况下做到这一点?

【问题讨论】:

标签: groovy


【解决方案1】:

您的问题的简短回答是否定的。

但是,我觉得这是为了排序。如果是这样的话。这是我为此目的使用的排序函数。

实际示例:Groovy Web Console

    Closure customSort = { String a, String b ->
      def c = a.isBigDecimal() ? new BigDecimal(a) : a
      def d = b.isBigDecimal() ? new BigDecimal(b) : b


      if (c.class == d.class) {
        return c <=> d
      } else if (c instanceof BigDecimal) {
        return -1
      } else {
        return 1
      }

    }

['foo','500','1000', '999', 'abc'].sort(customSort)

【讨论】:

  • 谢谢,不是为了那个目的。我用更多信息编辑了我的问题
  • 不要依赖异常,使用String.isInteger():c = a.integer ? a.toInteger() : a
  • 谢谢 - 不知道那里有
猜你喜欢
  • 1970-01-01
  • 2020-12-19
  • 2012-08-12
  • 1970-01-01
  • 1970-01-01
  • 2013-05-06
  • 2013-11-12
  • 2011-09-13
  • 1970-01-01
相关资源
最近更新 更多