Question

I'm trying to run a few calculations in order to represent a particular price (ie 20.30).

I have tried the Float#round method, but the instance variables holding these values eventually start representing numbers that look like 24.43418 after a few calculations.

This is just a method I created to turn a users input into a percentage

class Fixnum
 def percentage
  self.to_f / 100
 end
end

The @bankroll_amount and @risk_amount values should be evaluating to two decimal points

class Client

 def initialize(bankroll, unit)
  @bankroll_amount = bankroll.to_i.round(2)
  @unit_percentage = unit.to_i.percentage
  default_risk_amount.round(2)
  evaluate_default_unit!.round(2)
 end

 def default_risk_amount
  @risk_amount = @unit_percentage * @bankroll_amount
  @risk_amount.round(2)
 end

 # simulates what an updated bankroll looks like after a win based on clients "unit"  amount
 def risk_win
  @bankroll_amount = @bankroll_amount + @risk_amount
  @bankroll_amount.round(2)
  evaluate_default_unit!.round(2)
 end

 # simulates what a clients updated bankroll looks like after a loss based on clients "unit" amount
 def risk_loss
  @bankroll_amount = @bankroll_amount - @risk_amount
  evaluate_default_unit!
 end


 def evaluate_default_unit!
  @risk_amount = @unit_percentage * @bankroll_amount.round(2)
 end

end

Im not sure if this has anything to do with the fact that I am initializing these instance variables or not, but the @risk_amount returns the correct two decimal value, but when I return the object, the instance variable inside has running decimals.

c = Client.new 2000, 1
<Client:0x000001018956a0 @bankroll_amount=2000.0, @unit_percentage=0.01, @risk_amount=20.0>

c.risk_win
=> 20.2

When I run c.risk_win enough, it eventually returns

c
<Client:0x000001018956a0 @bankroll_amount=2440.3802, @unit_percentage=0.01, @risk_amount=24.4038>
Was it helpful?

Solution 2

Use number_with_precision to format the display of your floating point numbers to 2 decimal places:

number_with_precision(@bankroll_amount.to_f, precision: 2)

Usage in rails console:

[1] pry(main)> include ActionView::Helpers::NumberHelper
=> Object
[2] pry(main)> number_with_precision(2440.3802, precision: 2)
=> "2440.38"

OTHER TIPS

This is one way to show only two decimal points.

price = 20.21340404
"%.2f" % price
# => 20.23

Also see RAILS number_to_currency helpers ActionView::Helpers::NumberHelper

http://api.rubyonrails.org/classes/ActionView/Helpers/NumberHelper.html#method-i-number_to_currency

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top