Reputation: 1329
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
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
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
Reputation: 2156
You can just use the unary -
operator:
def negate_amount
-model.amount
end
Upvotes: 18