2013-03-21 305 views
0

,该怎么办错了:Groovy的数字字符串比较

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 

有没有一种办法在不将值转换为数值类型的情况下执行此操作

+0

这是在排序中使用? – 2013-03-21 22:26:47

+0

http://stackoverflow.com/questions/1262239/natural-sort-order-string-comparison-in-java-is-one-built-in – 2013-03-21 22:52:19

+0

我添加了一些更多的信息。这不是为了订购目的 – Thermech 2013-03-22 17:05:49

回答

0

你的问题的简短答案是否定的。

但是,我有一种感觉,这是为了排序的目的。如果是这样的话。这是我为此使用的排序功能。

例子在行动: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) 
+0

谢谢,它不是为了这个目的。我用更多信息编辑了我的问题 – Thermech 2013-03-21 23:24:26

+0

而不是依靠例外,使用[String.isInteger()](http://groovy.codehaus.org/groovy-jdk/java/lang/String.html#isInteger%28 %29):'c = a.integer? a.toInteger():a' – OverZealous 2013-03-22 00:27:24

+0

谢谢 - 不知道那是在那里 – 2013-03-22 02:11:49