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?
In Python, positive numbers can be changed to negativenegativeSubtraction is signified by the minus sign, −.https://en.wikipedia.org › wiki › SubtractionSubtraction - Wikipedia numbers with the help of the in-built method provided in the Python library called abs (). When abs () is used, it converts negative numbers to positive. However, when -abs () is used, then a positive number can be changed to a negative number.
Method #1 – Multiply by NegativeNegativeSubtraction is signified by the minus sign, −.https://en.wikipedia.org › wiki › SubtractionSubtraction - Wikipedia 1 with a Formula We can write a formula to multiply the cell's value by negative 1 (-1). This works on cells that contain either positive or negative numbers. The result of the formula is: Positive numbers will be converted to negative numbers.
To convert positive int to negative and vice-versa, use the Bitwise Complement Operator.
You can just use the unary -
operator:
def negate_amount
-model.amount
end
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With