Forums
New posts
Search forums
Members
Current visitors
Log in
Register
What's new
Search
Search
Search titles only
By:
New posts
Search forums
Menu
Log in
Register
Install the app
Install
Forums
Archive
Archive
Ruby
Rounding to X digits
JavaScript is disabled. For a better experience, please enable JavaScript in your browser before proceeding.
You are using an out of date browser. It may not display this or other websites correctly.
You should upgrade or use an
alternative browser
.
Reply to thread
Message
[QUOTE="Eric Anderson, post: 4445985"] This seems like such a basic question yet I can't really find the answer anywhere in the docs (I'm probably looking in the wrong place). Anyway I need to compute a percentage and output it. The percentage should be in the form 39.45% (i.e. round to the nearest two decimal places). So I have top = 68 bottom = 271 percentage = (top.to_f / bottom * 100 * 100).round.to_f / 100 The above works but it does not seem very intuitive. What I would rather is: percentage = (top.to_f / bottom).round(4) * 100 But round does not take any arguments on how many decimal places I want. It just assumes I don't want any. Perhaps there is another function that I am not seeing that will round while keeping a certain number of decimal places. Obviously I could also enhance round to take an optional argument but I wanted to see if there was an already existing function in the Ruby std library that will do it for me. Thanks, Eric [/QUOTE]
Verification
Post reply
Forums
Archive
Archive
Ruby
Rounding to X digits
Top