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.
- multiply by 1000
- cast to int
- 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
精彩评论