2012-12-07 81 views
1

如果some_float爲零,我希望結果爲0。我怎麼做?如果值爲零,則默認爲零

some_float = 9.238 
or 
some_float = nil 

some_float.round(2) 
+0

另見這個答案:http://stackoverflow.com/a/953388/44853 –

回答

9

只需撥打一個.to_f前一輪

some_float.to_f.round(2) 

因爲當你在零稱之爲to_f,它會返回0.0

9.238.to_f.round(2) # => 9.24 
nil.to_f.round(2) # => 0.0 
1

@塞爾吉奧的解決方案是更Rubyesque,但概念信任to_f這樣的「非感性」輸出有點可疑(爲什麼是nil.to_f 0.0而不是1.0這件事?這也是一個不錯的數字)。寫一個比較正統的方法是沒什麼可羞愧的:

some_float ? some_float.round(2) : 0.0 

當然,這看起來有點冗長,但你總是可以選擇使用Ruby的許多可能/期權模式之一。我個人使用Ickmaybe

some_float.maybe.round(2) || 0.0