ios Swift - 转换为绝对值

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/24159627/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-31 00:48:43  来源:igfitidea点击:

Swift - Convert to absolute value

iosiphoneswift

提问by Niko Adrianus Yuwono

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.

我已经尝试使用 UInt() 假设它将 Int 转换为无符号值,但它没有用。

回答by B.S.

The standard abs()function works great here:

标准abs()函数在这里很好用:

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

回答by Imanou Petit

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

使用 Swift 5,您可以使用以下两种方法之一将整数转换为其绝对值。



#1. Get absolute value of an Intfrom magnitudeproperty

#1. 获取Intfrommagnitude属性的绝对值

Inthas a magnitudeproperty. magnitudehas the following declaration:

Int有一个magnitude属性。magnitude有以下声明:

var magnitude: UInt { get }

For any numeric value x, x.magnitudeis the absolute value of x.

对于任何数值xx.magnitude是 的绝对值x

The following code snippet shows how to use magnitudeproperty in order to get the absolute value on an Intinstance:

以下代码片段显示了如何使用magnitude属性来获取Int实例的绝对值:

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


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

#2. 获取Intfromabs(_:)方法的绝对值

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

Swift 有一个名为abs(_:)method的全局数值函数。abs(_:)有以下声明:

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 Intinstance:

以下代码片段显示了如何使用abs(_:)全局函数来获取Int实例的绝对值:

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

回答by Sourabh Kumbhar

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

回答by Hamed

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

如果要从 double 或 Int 获取绝对值,请使用fabsfunc:

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