membersound
membersound

Reputation: 86627

How to convert a number always to be negative?

Math.abs() converts any number to positive. Is there also a function (that I might be missing) that supports the other way around: convert any number (no matter of sign) to a negative number?

The only thing I could imagine is: Math.abs(number) * -1

Upvotes: 9

Views: 16611

Answers (3)

Emmanuel Loisance
Emmanuel Loisance

Reputation: 726

In kotlin you can use unaryMinus

input = input.unaryMinus()

https://kotlinlang.org/api/latest/jvm/stdlib/kotlin/-int/unary-minus.html

Upvotes: 11

vbezhenar
vbezhenar

Reputation: 12316

Just as alternative solution you could use something like

int y = x < 0 ? x : -x;

but - abs(x) is more readable IMO.

Upvotes: 0

OPK
OPK

Reputation: 4180

You can just put - in front of the abs, such as this -Math.abs()

Upvotes: 23

Related Questions