# Percentage in Ruby

Hi all,

How to write percentage in Ruby, for instance 1.2%? Do I have to change
it to 0.012 before I apply other operation on it? It looks like “%” is
used for other purpose in Ruby.

Thanks,

Li

Li Chen wrote:

Hi all,

How to write percentage in Ruby, for instance 1.2%? Do I have to change
it to 0.012 before I apply other operation on it? It looks like “%” is
used for other purpose in Ruby.

Thanks,

Li

Try printf("%2.2f%", 1.2) ==> displays 1.20%

Li Chen wrote:

Hi all,

How to write percentage in Ruby, for instance 1.2%? Do I have to change
it to 0.012 before I apply other operation on it? It looks like “%” is
used for other purpose in Ruby.

Thanks,

Li

Yes, % is the modulo operator, so 1.2 percent would indeed be best
represented as 0.012 in your code.

Tom

Thank you all for the inputs.

Li

% is the modulo operator
http://www.ruby-doc.org/docs/ProgrammingRuby/html/ref_c_numeric.html

Tom W. wrote:

Yes, % is the modulo operator, so 1.2 percent would indeed be best
represented as 0.012 in your code.

You could also consider adding a percent method to Numeric:

class Numeric
def percent
self / 100.0
end
end

Then the following will work:

assert_equal(1.percent, 0.01)
assert_equal(1.5.percent, 0.015)

cheers,
mick