Calculate percentage in ruby?
You mean like this percentage = a/b*100
?
Update based on your new description:
class Numeric
def percent_of(n)
self.to_f / n.to_f * 100.0
end
end
# Note: the brackets () around number are optional
p (1).percent_of(10) # => 10.0 (%)
p (200).percent_of(100) # => 200.0 (%)
p (0.5).percent_of(20) # => 2.5 (%)
pizza_slices = 5
eaten = 3
p eaten.percent_of(pizza_slices) # => 60.0 (%)
Based on Mladen's code.
How to calculate percentages with rounding
OK, I think we can separate two answers here. First of all, you have to pay attention with rounding and truncating values. It could be dangerous in terms of inconsistent information. Anyways, based on your case, here it is.
If you want to display only integers and ignore the decimal part of the number, you can use either ceil or floor
0.47939999999999994.ceil
#=> 1
0.47939999999999994.floor
#=> 0If you want to round your decimal, you can use round passing the precision desired:
0.47939999999999994.round
#=> 0
0.47939999999999994.round(1)
#=> 0.5
0.47939999999999994.round(2)
#=> 0.48
0.47939999999999994.round(3)
#=> 0.479
0.47939999999999994.round(4)
#=> 0.4794
Your method should look like the following (using round
)
def self.percent
((Order.revenue.to_f.round(2) / Order.goal.to_f.round(2)) * 100).round(2)
end
I hope it helps !
Ruby calculate the percentage of elements in hash
You can use Enumerable#each_with_object
:
sum = a.values.inject(0, :+) # or simply a.values.sum if you're on Ruby 2.4+
#=> 12
a.each_with_object({}) { |(k, v), hash| hash[k] = v * 100.0 / sum }
#=> {"str1"=>16.666666666666668, "str2"=>25.0, "str3"=>58.333333333333336}
To have it with %
:
a.each_with_object({}) { |(k, v), hash| hash[k] = "#{(v * 100.0 / sum).round(2)}%" }
#=> {"str1"=>"16.67%", "str2"=>"25.0%", "str3"=>"58.33%"}
Calculating percentage returns integer
Cast one of price
or discount_percentage
to float:
price*(discount_percentage.to_f/100)
Number of Percentage in Ruby on Rails
Your discount percentage calculation is off. You need to find the difference between the original price and the new price. And divide it by the original price to get the discount percentage:
def percentage_off
(Float(original_deal - our_deal) / original_deal * 100).ceil
end
Your input example would now return (100 - 90) / 100 * 100 = 10
Percentage Calculation - Ruby on Rails
How about:
percentages = p.towns.group_by(&:ocean).map {|ocean, towns| [ocean, (towns.count/p.towns.count.to_f * 100).round(0)]}.to_h
perentages.each {|ocean, percentage| puts "Ocean #{ocean}: #{percentage}%"}
How to convert float to percentage in Ruby
To convert a float to a percentage, multiply the float by 100. If you need to output it with the % sign, use string interpolation inside a string.
Example:
percentage_value = 0.02 * 100
puts "#{percentage_value}%"
2.0%
{edited}
how to calculate percentage for nested fields in ruby on rails
There is child_index
thing that rails provide in nested association when using in html.erb.
Below code may resolve your problem.
<div class="education_<%= f.options[:child_index] %>">
<div class="form-group">
<%= f.label :max_marks %><br>
<%= f.text_field :max_marks, class: 'max_marks', data: {index: f.options[:child_index]} %>
</div>
<div class="form-group">
<%= f.label :marks_obtained %><br>
<%= f.text_field :marks_obtained, class: 'marks_obtained', data: {index: f.options[:child_index]}%>
</div>
<div class="form-group">
<%= f.label :percentage %><br>
<%= f.text_field :percentage, class: 'percentage' %>
</div>
</div>
$('.max_marks, .marks_obtained').focusout(function(event){
var target = $(event.target), parent = target.parents().find('.education_' + target.attr('data-index'));
if (parseInt(parent.find('.marks_obtained').val()) > parseInt(parent.find('.max_marks').val())){
alert('Marks Obtained cannot be greater then Maximun Marks');
parent.find('.marks_obtained').val('');
} else {
var max_marks = parseFloat(parent.find('.max_marks').val())
var marks_obtained = parseFloat(parent.find('.marks_obtained').val())
max_marks = max_marks === NaN ? 0 : max_marks
marks_obtained = marks_obtained === NaN ? 0 : marks_obtained
parent.find('.percentage').val(marks_obtained * 100 / max_marks)
}
});
Ruby calculate percentages of array objects
I would use the group by function:
my_array = ["one", "two", "two", "three"]
percentages = Hash[array.group_by{|x|x}.map{|x, y| [x, 1.0*y.size/my_array.size]}]
p percentages #=> {"one"=>0.25, "two"=>0.5, "three"=>0.25}
final = array.map{|x| percentages[x]}
p final #=> [0.25, 0.5, 0.5, 0.25]
Alternative 2 without group_by:
array, result = ["one", "two", "two", "three"], Hash.new
array.uniq.each do |number|
result[number] = array.count(number)
end
p array.map{|x| 1.0*result[x]/array.size} #=> [0.25, 0.5, 0.5, 0.25]
Related Topics
Count the Number of Lines in a File Without Reading Entire File into Memory
Ruby/Rails CSV Parsing, Invalid Byte Sequence in Utf-8
How to Get Constants Defined by Ruby's Module Class via Reflection
Ruby Loading Config (Yaml) File in Same Dir as Source
How to Read a Password from the Command Line in Ruby
When to Call a "Require" in Rails
Rails Fields_For Form Not Showing Up, Nested Form
Adding a Staging Environment to the Workflow
How to Install Ruby on Rails 3 on Osx
How to Manage Multiple Gemsets and Ruby Versions with Rvm
Ruby: How to Iterate Over an Array of Hashes and Return the Values in a Single String
Bcrypt Error: Devise Ruby 2.0 and Rails 4.0
How to Install (Build) Ruby 1.9.3 on Osx Lion
Creating Signature and Nonce for Oauth (Ruby)
What's the Best Way to Deploy a Jruby on Rails Application to Tomcat
Accessing Config from Application.Rb in Controller (Rails 3)