E
Eric Anderson
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
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