Round a ruby float up or down to the nearest 0.05

后端 未结 9 1673
日久生厌
日久生厌 2020-12-29 04:43

I\'m getting numbers like

2.36363636363636
4.567563
1.234566465448465
10.5857447736

How would I get Ruby to round these numbers up (or dow

相关标签:
9条回答
  • 2020-12-29 05:02

    less precise, but this method is what most people are googling this page for

    (5.65235534).round(2)
    #=> 5.65
    
    0 讨论(0)
  • 2020-12-29 05:02

    Ruby 2 now has a round function:

    # Ruby 2.3
    (2.5).round
     3
    
    # Ruby 2.4
    (2.5).round
     2
    

    There are also options in ruby 2.4 like: :even, :up and :down e.g;

    (4.5).round(half: :up)
     5
    
    0 讨论(0)
  • 2020-12-29 05:06

    In general the algorithm for “rounding to the nearest x” is:

    round(x / precision)) * precision
    

    Sometimes is better to multiply by 1 / precision because it is an integer (and thus it works a bit faster):

    round(x * (1 / precision)) / (1 / precision)
    

    In your case that would be:

    round(x * (1 / 0.05)) / (1 / 0.05)
    

    which would evaluate to:

    round(x * 20) / 20;
    

    I don’t know any Python, though, so the syntax might not be correct but I’m sure you can figure it out.

    0 讨论(0)
提交回复
热议问题