Re: [問題] 小數的四捨五入

看板Ruby作者 (godfat 真常)時間17年前 (2007/11/14 08:09), 編輯推噓0(000)
留言0則, 0人參與, 最新討論串2/5 (看更多)
※ 引述《shelary (台中喵小咩)》之銘言: : 環境: : Ruby 1.8.6 : 狀況: : ruby 的 round method 好像只能取 整數 : 例如: : (1.5).round ==>> 2 : (-1.5).round ==>> -2 : 可是如果我希望像 excel 的 ROUND 函數一樣 : ROUND(數字, 取到小數的第幾位數) : 例如: : ROUND(1.2345, 3) ==>> 1.235 : ROUND(1.2345, 1) ==>> 1.2 : ROUND(1.2345, 0) ==>> 1 : 像這樣的功能應該怎麼寫比較好呢? 可以考慮灌個 facets... gem install facets 這已經是我必用的 gem 了 :o 裡面有很多好用的 tool http://facets.rubyforge.org/rdoc/Core/classes/Float.html#M000167 不過有時候不便在 server 上東灌西灌東西,查他 source copy & paste 也 ok. # File facets/numeric/round.rb, line 61 def round_at( d ) #d=0 (self * (10.0 ** d)).round_off.to_f / (10.0 ** d) end Float#round_off is simple an alias for Float#round. 或是用推文提到的 sprintf 也可以,只是怪怪的就是了 -- Hear me exalted spirits. Hear me, be you gods or devils, ye who hold dominion here: I am a wizard without a home. I am a wonderer seeking refuge. Sacrifice -- ※ 發信站: 批踢踢實業坊(ptt.cc) ◆ From: 220.135.28.18
文章代碼(AID): #17EZpIUp (Ruby)
文章代碼(AID): #17EZpIUp (Ruby)