Stupid question:

How do i convert a negative integer to a positive integer or how do i only get the numbers from the negative integer?

Lets say i have -12345 and i want to get 12345.

Stupid question:

How do i convert a negative integer to a positive integer or how do i only get the numbers from the negative integer?

Lets say i have -12345 and i want to get 12345.

thanks

Historically, basic languages have used the Abs() function, which is still the case in Xojo. Returns the absolute value of a number, e.g. positive.

Cheers

Grant

Multiply by -1?

Yes and no.

Yes in that multiplying a negative number by -1 will return a positive.

No in that a positive number will return it’s negative equivalent when multiplying by -1. You would have to use an `if...then`

statement.

Using the Abs() function gives you the required result in one line of code.

Cheers

Grant

[quote=183952:@Grant Singleton]Yes and no.

Yes in that multiplying a negative number by -1 will return a positive.

No in that a positive number will return it’s negative equivalent when multiplying by -1. You would have to use an `if...then`

statement.

Using the Abs() function gives you the required result in one line of code.[/quote]

Indeed. However, since the OP asked to convert a negative number into a positive one, I supposed he will handle negative numbers only - in which case a *-1 would be sufficient (and likely faster). Anyway, if any number (be it positive or negative) may occur, ABS() is the way to go

`Dim result As Integer = Bitwise.OnesComplement(value) + 1`

Well, while we are on the subject of obscure ways to do this instead of simply using ABS, how about

result = Floor(SQRT(value^2))

Both ABS() and SQRT will return double values.

You may want to user Floor() to flatten it to an integer, or assign the result to an integer variable.

result = max(value, -value)

value = -value

`If(value>=0,value,-value)`

maintains datatype integrity

Forum for Xojo Programming Language and IDE. Copyright © 2024 Xojo, Inc.