Ruby: Rounding float in Ruby

156,479

Solution 1

When displaying, you can use (for example)

>> '%.2f' % 2.3465
=> "2.35"

If you want to store it rounded, you can use

>> (2.3465*100).round / 100.0
=> 2.35

Solution 2

Pass an argument to round containing the number of decimal places to round to

>> 2.3465.round
=> 2
>> 2.3465.round(2)
=> 2.35
>> 2.3465.round(3)
=> 2.347

Solution 3

you can use this for rounding to a precison..

//to_f is for float

salary= 2921.9121
puts salary.to_f.round(2) // to 2 decimal place                   

puts salary.to_f.round() // to 3 decimal place          

Solution 4

You can add a method in Float Class, I learnt this from stackoverflow:

class Float
    def precision(p)
        # Make sure the precision level is actually an integer and > 0
        raise ArgumentError, "#{p} is an invalid precision level. Valid ranges are integers > 0." unless p.class == Fixnum or p < 0
        # Special case for 0 precision so it returns a Fixnum and thus doesn't have a trailing .0
        return self.round if p == 0
        # Standard case  
        return (self * 10**p).round.to_f / 10**p
    end
end

Solution 5

You can also provide a negative number as an argument to the round method to round to the nearest multiple of 10, 100 and so on.

# Round to the nearest multiple of 10. 
12.3453.round(-1)       # Output: 10

# Round to the nearest multiple of 100. 
124.3453.round(-2)      # Output: 100
Share:
156,479

Related videos on Youtube

user211662
Author by

user211662

Updated on June 27, 2021

Comments

  • user211662
    user211662 almost 3 years

    I'm having problems rounding. I have a float, which I want to round to the hundredth of a decimal. However, I can only use .round which basically turns it into an int, meaning 2.34.round # => 2. Is there a simple effect way to do something like 2.3465 # => 2.35

  • Mark Embling
    Mark Embling over 14 years
    This would seem more sensible than multiplying, rounding and dividing. +1
  • Mindey I.
    Mindey I. about 13 years
    Hmm this method doesn't seem to be in ruby 1.8.7. Maybe in 1.9?
  • Steve Weet
    Steve Weet about 13 years
    @Brian. This is definitely in 1.9 and is also in rails (Which this question was tagged with)
  • Noah Sussman
    Noah Sussman about 12 years
    Thanks. I didn't realize sprintf would take care of rounding for me. sprintf '%.2f', 2.3465 also works.
  • bobmagoo
    bobmagoo over 11 years
    Ruby 1.8.7's round method doesn't have this ability, adding the decimal place rounding parameter is a 1.9 ability
  • TheOneTeam
    TheOneTeam over 10 years
    value.round(2) is better than this solution
  • Excalibur
    Excalibur about 10 years
    Keep in mind that 2.3000.round(2) => 2.3 and sprintf '%.2f', 2.300 => 2.30. In my opinion this is a flaw in round(), or it should have an option to preserve trailing zeros.
  • Roobie Nuby
    Roobie Nuby about 10 years
    @Excalibur 2.3000.round(2) is a number, not a string. There is no way that the number 2.3 is different from 2.30, so there is no way to have an option to preserve trailing zeros. You could make your own class of numbers_with_significance but then we already have strings.
  • Smar
    Smar almost 9 years
    Note that number_with_precision is Rails-only method.
  • likethesky
    likethesky over 7 years
    Note that although this does work for two decimal places, there's a flaw in '%.3f' % 1.2345 (3 decimal places, not 2), however!! Same for sprintf as well. Beware. That will return => 1.234 not => 1.235 as most would expect (iow, after the 2nd decimal, sprintf rounds 5 down and only rounds a 6 up). That's why Kit Ho's comment above has 25+ upvotes. Safer to use, '%.3f' % 1.2345.round(3) so the number is properly rounded by .round first, then formatted (with trailing zeros, if need be).
  • NotAnAmbiTurner
    NotAnAmbiTurner over 6 years
    Note that you don't get trailing zeros with this, so 1.1.round(2) => 1.1 not 1.10
  • NAREN PUSHPARAJU
    NAREN PUSHPARAJU about 5 years
    Is there any way to avoid rounding of the numbers that doesn't have any decimels in it ? like if it is 0 it should as 0 and not 0.0
  • ralphmerridew
    ralphmerridew about 4 years
    sprintf rounds 0.5 to the nearest even digit. '%.3f' % 1.2355 and '%.3f' % 1.2365 both give "1.236" .round rounds 0.5 up
  • Pablo
    Pablo over 3 years
    2.4.round(3) => 2.4