rukia_kuchiki_21
rukia_kuchiki_21

Reputation: 1329

Convert positive integer to negative integer

  def negate_amount
    amount = model.amount.to_s
    ("-" + amount).to_i
  end

is there a better way to turn positive integer to negative?

The code above works, but is there a ruby or rails function for that? Without doing math operations?

Upvotes: 10

Views: 29863

Answers (4)

Josh
Josh

Reputation: 511

Similar question to How do I convert a positive number to negative?. But in summary, if you are always expecting a negative answer you could simply say

def negate_amount
    amount = -(model.abs)
end

Otherwise, if you simply want the function to return a negative of the integer : assuming negating a negative number returns a positive number, then you would use

def negate_amount
    amount = -(model)
end

Upvotes: 13

Vince Banzon
Vince Banzon

Reputation: 1489

How about if you multiply it by negative one?

  def negate_amount
    amount = model.amount.to_s
    amount = amount*-1
  end

Upvotes: 2

mooiamaduck
mooiamaduck

Reputation: 2156

You can just use the unary - operator:

def negate_amount
    -model.amount
end

Upvotes: 18

João Maia
João Maia

Reputation: 91

You can just multiply per -1 the amount.

Upvotes: 3

Related Questions