rubynumbersintegerfixnum

How do I always round a number down in Ruby?


For example, if I want 987 to equal "900".


Solution

  • n = 987
    m = 2
    
    n.floor(-m)
      #=> 900
    

    See Integer#floor: "When the precision is negative, the returned value is an integer with at least ndigits.abs trailing zeros."

    or

    (n / 10**m) * 10**m
      #=> 900