开发者

How to discard float precision in Ruby

I want to discard float precision.

(4.43597).discard(3)   =>   4.435 (not 4.436)

I don't want to use round. How should I do it ? I can't find of a way开发者_StackOverflow.


  1. multiply by 1000
  2. cast to int
  3. divide by 1000.0


Still use round, but have the effect of truncating at the desired position.

(4.43597-0.0005).round(3)


A bit overkill, but nonetheless,

>> (4.43597).to_s.scan(/\d+\.\d{3}/)[0].to_f
=> 4.435


Another option:
1. multiply by 1000
2. use floor() to round down
3. divide by 1000.0

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜