[lnkForumImage]
TotalShareware - Download Free Software

Confronta i prezzi di migliaia di prodotti.
Asp Forum
 Home | Login | Register | Search 


 

Forums >

comp.lang.ruby

percentage in Ruby

Li Chen

8/3/2007 10:04:00 PM

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-....

5 Answers

Michael W. Ryder

8/3/2007 10:15:00 PM

0

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%

Tom Werner

8/3/2007 10:22:00 PM

0

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

Kevin Brown

8/3/2007 10:49:00 PM

0


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




-----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-....


Li Chen

8/4/2007 1:01:00 PM

0

Thank you all for the inputs.

Li
--
Posted via http://www.ruby-....

Michael Hollins

8/4/2007 2:12:00 PM

0

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