Swift - Convert to absolute value

IosIphoneSwift

Ios Problem Overview


is there any way to get absolute value from an integer?
for example

-8  
to  
 8

I already tried to use UInt() assuming it will convert the Int to unsigned value but it didn't work.

Ios Solutions


Solution 1 - Ios

The standard abs() function works great here:

let c = -8
print(abs(c))
// 8

Solution 2 - Ios

With Swift 5, you may use one of the two following ways in order to convert an integer to its absolute value.


#1. Get absolute value of an Int from magnitude property

Int has a magnitude property. magnitude has the following declaration:

var magnitude: UInt { get }

>For any numeric value x, x.magnitude is the absolute value of x.

The following code snippet shows how to use magnitude property in order to get the absolute value on an Int instance:

let value = -5
print(value.magnitude) // prints: 5

#2. Get absolute value of an Int from abs(_:) method

Swift has a global numeric function called abs(_:) method. abs(_:) has the following declaration:

func abs<T>(_ x: T) -> T where T : Comparable, T : SignedNumeric

>Returns the absolute value of the given number.

The following code snippet shows how to use abs(_:) global function in order to get the absolute value on an Int instance:

let value = -5
print(abs(value)) // prints: 5

Solution 3 - Ios

If you want to force a number to change or keep it positive.
Here is the way:

abs() for int
fabs() for double
fabsf() for float

Solution 4 - Ios

If you want to get absolute value from a double or Int, use fabs func:

var c = -12.09
print(fabs(c)) // 12.09
c = -6
print(fabs(c)) // 6

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionNiko Adrianus YuwonoView Question on Stackoverflow
Solution 1 - IosB.S.View Answer on Stackoverflow
Solution 2 - IosImanou PetitView Answer on Stackoverflow
Solution 3 - IosSourabh KumbharView Answer on Stackoverflow
Solution 4 - IosHamedView Answer on Stackoverflow