将正整数转换为负整数

时间:2021-11-21 15:57:11
  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?

上面的代码是有效的,但是有ruby或rails函数吗?不做数学作业吗?

4 个解决方案

#1


8  

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

#2


7  

You can just use the unary - operator:

你可以使用一元运算符:

def negate_amount
    -model.amount
end

#3


1  

You can just multiply per -1 the amount.

只要乘以-1就可以了。

#4


1  

How about if you multiply it by negative one?

如果乘以- 1呢?

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

#1


8  

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

#2


7  

You can just use the unary - operator:

你可以使用一元运算符:

def negate_amount
    -model.amount
end

#3


1  

You can just multiply per -1 the amount.

只要乘以-1就可以了。

#4


1  

How about if you multiply it by negative one?

如果乘以- 1呢?

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