Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 467
rukia_kuchiki_21 Avatar asked Aug 19 '15 00:08

rukia_kuchiki_21


People also ask

How do I turn a positive number negative in Python?

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.

How do I turn a positive into a negative in Excel?

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.

How do you change positive to negative in Java?

To convert positive int to negative and vice-versa, use the Bitwise Complement Operator.


2 Answers

You can just use the unary - operator:

def negate_amount
    -model.amount
end
like image 101
mooiamaduck Avatar answered Oct 02 '22 18:10

mooiamaduck


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
like image 36
Josh Avatar answered Oct 02 '22 20:10

Josh