user11736353
user11736353

Reputation: 87

Add percentage to number in Ruby

How can I add a percentage to a number in Ruby?

In this example I want to add 20% to 32.92:

irb(main):001:0> 32.92 * (1 + (20 / 100))
=> 32.92

Google answers with the correct answer; 39.50.

Upvotes: 2

Views: 1995

Answers (2)

41 72 6c
41 72 6c

Reputation: 1780

Lets say your base_value is: 39.92. Your markup is 20.

Integer division will lead to the following:

20 / 100
# => 0

So irb is the right direction. This gives better results:

20.to_f / 100
# => 0.2

So the final calculation will look like this:

final_value = (base_value + (markup.to_f / 100) * base_value).round

This gives you the expected value.

As you don’t mind the result to be floored instead of rounded it’s possible to get correct result using integer division:

final_value = base_value + base_value * markup / 100

Upvotes: 6

Marek Lipka
Marek Lipka

Reputation: 51151

20 / 100 returns 0, because it's integer division if you pass integers as arguments. Instead, you can pass floats, like this:

32.92 * (1 + (20.0 / 100.0))

or do simply:

32.92 * 1.2

Upvotes: 5

Related Questions