IT

스위프트에서 Float를 Int로 변환

lottoking 2020. 5. 13. 08:22
반응형

스위프트에서 Float를 Int로 변환


나는를 변환 할 FloatInt스위프트있다. 이러한 유형의 캐스팅 은 Objective-C의 floats 및 ints 와 달리 기본 유형이 아니기 때문에 작동하지 않습니다.

var float: Float = 2.2
var integer: Int = float as Float

그러나 이것은 다음과 같은 오류 메시지를 생성합니다.

'Float'은 'Int'로 변환 할 수 없습니다

모든 아이디어를 어떻게에서 속성 변환에 FloatInt?


Swift에서 다음과 같이 변환 Float수 있습니다 Int.

var myIntValue:Int = Int(myFloatValue)
println "My value is \(myIntValue)"

@paulm의 주석 으로이 결과를 얻을 수도 있습니다.

var myIntValue = Int(myFloatValue)

명시 적 변환

Int로 변환하면 정밀도가 떨어집니다 (효과적으로 내림). 수학 라이브러리에 액세스하면 명시 적 변환을 수행 할 수 있습니다. 예를 들면 다음과 같습니다.

당신이 원한다면 라운드 아래로 정수로 변환 :

let f = 10.51
let y = Int(floor(f))

결과는 10입니다.

당신이 원한다면 반올림 과 정수로 변환 :

let f = 10.51
let y = Int(ceil(f))

결과는 11입니다.

가장 가까운 정수명시 적으로 반올림 하려는 경우

let f = 10.51
let y = Int(round(f))

결과는 11입니다.

후자의 경우 이것은 의미가 없어 보이지만 암시 적 변환이 없기 때문에 의미 상 더 명확합니다. 예를 들어 신호 처리를 수행하는 경우 중요합니다.


변환은 간단합니다.

let float = Float(1.1) // 1.1
let int = Int(float) // 1

그러나 안전하지 않습니다.

let float = Float(Int.max) + 1
let int = Int(float)

멋진 충돌로 인한 의지 :

fatal error: floating point value can not be converted to Int because it is greater than Int.max

그래서 오버플로를 처리하는 확장을 만들었습니다.

extension Double {
    // If you don't want your code crash on each overflow, use this function that operates on optionals
    // E.g.: Int(Double(Int.max) + 1) will crash:
    // fatal error: floating point value can not be converted to Int because it is greater than Int.max
    func toInt() -> Int? {
        if self > Double(Int.min) && self < Double(Int.max) {
            return Int(self)
        } else {
            return nil
        }
    }
}


extension Float {
    func toInt() -> Int? {
        if self > Float(Int.min) && self < Float(Int.max) {
            return Int(self)
        } else {
            return nil
        }
    }
}

나는 이것이 누군가를 도울 수 있기를 바랍니다.


숫자를 정확하게 반올림하는 방법은 많이 있습니다. rounded()부동 소수점을 원하는 정밀도로 반올림 하려면 swift의 표준 라이브러리 방법 사용해야 합니다.

라운드 사용 .up규칙 :

let f: Float = 2.2
let i = Int(f.rounded(.up)) // 3

라운드에 다운 을 사용 .down규칙 :

let f: Float = 2.2
let i = Int(f.rounded(.down)) // 2

To round to the nearest integer use .toNearestOrEven rule:

let f: Float = 2.2
let i = Int(f.rounded(.toNearestOrEven)) // 2

Be aware of the following example:

let f: Float = 2.5
let i = Int(roundf(f)) // 3
let j = Int(f.rounded(.toNearestOrEven)) // 2

Like this:

var float:Float = 2.2 // 2.2
var integer:Int = Int(float) // 2 .. will always round down.  3.9 will be 3
var anotherFloat: Float = Float(integer) // 2.0

You can get an integer representation of your float by passing the float into the Integer initializer method.

Example:

Int(myFloat)

Keep in mind, that any numbers after the decimal point will be loss. Meaning, 3.9 is an Int of 3 and 8.99999 is an integer of 8.


Use a function style conversion (found in section labeled "Integer and Floating-Point Conversion" from "The Swift Programming Language."[iTunes link])

  1> Int(3.4)
$R1: Int = 3

You can type cast like this:

 var float:Float = 2.2
 var integer:Int = Int(float)

Just use type casting

 var floatValue:Float = 5.4
 var integerValue:Int = Int(floatValue)

 println("IntegerValue = \(integerValue)")

it will show roundoff value eg: IntegerValue = 5 means the decimal point will be loss


var i = 1 as Int

var cgf = CGFLoat(i)

var floatValue = 10.23
var intValue = Int(floatValue)

This is enough to convert from float to Int


Suppose you store float value in "X" and you are storing integer value in "Y".

Var Y = Int(x);

or

var myIntValue = Int(myFloatValue)

Use Int64 instead of Int. Int64 can store large int values.

참고URL : https://stackoverflow.com/questions/24029917/convert-float-to-int-in-swift

반응형