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

···

--
Posted via http://www.ruby-forum.com/.

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

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

···

-----Original Message-----
From: list-bounce@example.com on behalf of Li Chen
Sent: Fri 8/3/2007 6:03 PM
To: ruby-talk ML
Subject: 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
--
Posted via http://www.ruby-forum.com/.

Thank you all for the inputs.

Li

···

--
Posted via http://www.ruby-forum.com/.

Tom Werner wrote:

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.

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