2013-09-23 43 views
2

我有這樣的代碼:Groovy和斯波克:toDouble VS toFloat

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 
[email protected] 
+2

http://floating-point-gui.de/ –

+1

嘗試:'particle1.x == -5.2f' –

+0

如果有人可以解釋downvote ,我可以在未來提出更好的問題。謝謝! –

回答

4

默認情況下,-5.2在Groovy是一個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的之間的比較雙:

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 

否則,根據@蒂姆的評論,使用-5.2f,所以比較是針對浮動對象進行:

def e = -5.2f 
def f = "-5.2".toFloat() 
assert e == f 
assert e.getClass() == Float 
assert f.getClass() == Float