Tuesday 15 March 2011

ruby - Rails: How to print a decimal as a percent? -



ruby - Rails: How to print a decimal as a percent? -

is there way print decimal percentage, 2 digits after period?

my decimals between 1 , 0, suppose work phone call number.round(2) starting 3rd character, can't find syntax anywhere.

to clarify, want number stored full decimal, printed percentage.

you going want utilize number_to_percentage method. here examples of how utilize it.

number_to_percentage(100) # => 100.000% number_to_percentage("98") # => 98.000% number_to_percentage(100, precision: 0) # => 100% number_to_percentage(1000, delimiter: '.', separator: ',') # => 1.000,000% number_to_percentage(302.24398923423, precision: 5) # => 302.24399% number_to_percentage(1000, locale: :fr) # => 1 000,000% number_to_percentage("98a") # => 98a% number_to_percentage(100, format: "%n %") # => 100 %

options:

:locale - sets locale used formatting (defaults current locale). :precision - sets precision of number (defaults 3). :significant - if true, precision # of significant_digits. if false, # of fractional digits (defaults false). :separator - sets separator between fractional , integer digits (defaults “.”). :delimiter - sets thousands delimiter (defaults “”). :strip_insignificant_zeros - if true removes insignificant zeros after decimal separator (defaults false). :format - specifies format of percentage string number field %n (defaults “%n%”).

or can write ruby following:

class numeric def percent_of(n) self.to_f / n.to_f * 100.0 end end p (1).percent_of(10) # => 10.0 (%) p (200).percent_of(100) # => 200.0 (%) p (0.5).percent_of(20) # => 2.5 (%)

ruby-on-rails ruby ruby-on-rails-4 decimal percentage

No comments:

Post a Comment