Andrew Lauer Barinov
Andrew Lauer Barinov

Reputation: 5754

Making sure Ruby treats numbers as decimals rather than floats

Suppose I have a method like:

def calculate(alpha, beta)
  # do stuff
end

How do I make sure that when I call calculate(1.0,2.0) it will always treat the arguments as decimals and not as floats or integers?

Upvotes: 1

Views: 122

Answers (2)

claudijd
claudijd

Reputation: 66

If you're looking for params to be handled as a BigDecimal, you can use the following:

    require 'bigdecimal'
    require 'bigdecimal/util'

    def calculate(alpha, beta)
      alpha_bigdec = alpha.to_d
      beta_bigdec = beta.to_d
    end

Upvotes: 4

richoffrails
richoffrails

Reputation: 1033

There is the BigDecimal class in the Ruby Standard Library

def calculate(alpha, beta)
  alpha = BigDecimal.new alpha
  beta = BigDecimal.new beta

  # rest of method here
end

You can then refer to the BigDecimal documentation to see which methods you can use to operate on it. A few I can think of off the top of my head are to_s, to_i, to_r, add, sub, etc.

Upvotes: 1

Related Questions