Rounding float in Ruby

后端 未结 9 1176
北恋
北恋 2020-12-12 13:33

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 in

相关标签:
9条回答
  • 2020-12-12 13:57

    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
    
    0 讨论(0)
  • 2020-12-12 13:59

    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          
    
    0 讨论(0)
  • 2020-12-12 14:03

    what about (2.3465*100).round()/100.0?

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