我有这个代码:
static def parseString(String inputRow, Particle particle) {
def map = inputRow.split()
particle.mass = map[0].toDouble()
particle.x = map[1].toDouble()
particle.y = map[2].toDouble()
}
这个测试代码:
static final inputRow = "1 -5.2 3.8"
def particle1 = new Particle()
def "string should be parsed into particles"() {
when:
RepulsionForce.parseString(inputRow, particle1);
then:
particle1.mass == 1
particle1.x == -5.2
particle1.y == 3.8
}
上述测试按原样通过; 但是,当我将 parseString 代码更改为以下代码时:
static def parseString(String inputRow, Particle particle) {
def map = inputRow.split()
particle.mass = map[0].toFloat()
particle.x = map[1].toFloat()
particle.y = map[2].toFloat()
}
相同的测试因以下错误而失败:
Condition not satisfied:
particle1.x == -5.2
| | |
| | false
| -5.2
Particle@a548695
最佳答案
默认情况下,Groovy 中的 -5.2
是 BigDecimal,因此您将 BigDecimal 与 Float 对象进行比较。这些通过:
def a = -5.2
def b = "-5.2".toFloat()
assert a != b
assert a.getClass() == BigDecimal
assert b.getClass() == Float
assert a.toFloat() == b
Groovy 接受 BigDecimal 和 Double 之间的比较:
def g = -5.2
def h = "-5.2".toDouble()
assert g == h
assert g.getClass() == BigDecimal
assert h.getClass() == Double
如果您需要进行一些需要精度的计算,您可能最好使用 BigDecimal,因为它们保留它(尽管会降低性能)
def c = -5.2
def d = "-5.2".toBigDecimal()
assert c == d
assert c.getClass() == BigDecimal
assert d.getClass() == BigDecimal
否则,根据 @Tim 的评论,使用 -5.2f
,因此针对 Float 对象进行比较:
def e = -5.2f
def f = "-5.2".toFloat()
assert e == f
assert e.getClass() == Float
assert f.getClass() == Float
关于Groovy 和 Spock : toDouble vs toFloat,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18962842/