我有这段代码:
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
答案 0 :(得分:5)
默认情况下,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