Multiple ways to parse to absolute number swift with code example
This tutorial explains how to calculate the absolute value of a number in Swift programming.
abs()
function for Int typefabs()
function for Double typefabsf()
function for Float type- Int
magnitude
The absolute value of a number returns a number by removing the negative sign.
For example, The input number is -123, And the absolute value is 123. If the number is 11 and the absolute value is 11.
There are multiple ways to convert to absolute value,
- One way is using the Int magnitude property and
- Another way using
abs
for Int,fabs
for double, andfabsf
for float types
Swift Convert to the absolute value
First Import the foundation
into the code to use these methods
abs()
function for Int typeIt returns the absolute value of a number.
import Foundation;
var number = -123
print(abs(number)) //123
number=1231
print(abs(number)) //1231
fabs()
function for Double typeIt returns the absolute value of a number.
import Foundation;
var number:Double = -123.123
print(fabs(number)) //123.123
fabsf()
function for Float type
The fabsf()
function accepts the Float type and returns absolute value.
import Foundation;
var number :Float = -123.123
print(fabsf(number))
- Use
Int magnitude
property of Int type
import Foundation;
var number = -345.123
print(number.magnitude) //345.123
Conclusion
There are multiple ways we can convert to absolute value for a given number. The number can be Int, Float, or Double type