Swift에서 부동을 Int로 변환
변환하고 싶다Float에 대해서Int스위프트에서.이와 같은 기본 캐스팅은 이러한 유형이 다음과 같이 원시적이지 않기 때문에 작동하지 않습니다.float및int목표-C의 s
var float: Float = 2.2
var integer: Int = float as Float
그러나 이로 인해 다음과 같은 오류 메시지가 나타납니다.
'플로트'는 'Int'로 변환할 수 없습니다.
다음에서 속성을 변환 방법Float로.Int?
변환할 수 있습니다.Float로.Int이렇게 Swift로:
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입니다.
후자의 경우, 이것은 현학적인 것처럼 보일 수 있지만, 암묵적인 변환이 없기 때문에 의미론적으로는 명확합니다.예를 들어 신호 처리를 하는 경우 중요합니다.
정확한 반올림 방법에는 여러 가지가 있습니다.최종적으로 Swift의 표준 라이브러리 메서드를 사용해야 합니다.rounded()원하는 정밀도로 플로트 번호를 반올림합니다.
용도를 반올림하다.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
가장 가까운 정수로 반올림하려면.toNearestOrEven규칙:
let f: Float = 2.2
let i = Int(f.rounded(.toNearestOrEven)) // 2
다음의 예에 주의해 주세요.
let f: Float = 2.5
let i = Int(roundf(f)) // 3
let j = Int(f.rounded(.toNearestOrEven)) // 2
변환은 간단합니다.
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
}
}
}
이게 누군가에게 도움이 됐으면 좋겠다
플로트를 Integer initializer 메서드에 전달하면 플로트의 정수 표현을 얻을 수 있습니다.
예:
Int(myFloat)
소수점 이후의 숫자는 모두 손실된다는 점에 유의하십시오.즉, 3.9는 Int 3이고 8.9999는 정수 8입니다.
다음과 같이 합니다.
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
함수 스타일 변환(Swift Programming Language의 "Integer and Floating Point Conversion" 섹션에 있음)을 사용합니다.[iTunes link]
1> Int(3.4)
$R1: Int = 3
캐스트를 다음과 같이 입력할 수 있습니다.
var float:Float = 2.2
var integer:Int = Int(float)
활자 주조만 사용
var floatValue:Float = 5.4
var integerValue:Int = Int(floatValue)
println("IntegerValue = \(integerValue)")
반올림 값이 표시됩니다(예: IntegerValue = 5는 소수점이 손실이 된다는 의미).
var floatValue = 10.23
var intValue = Int(floatValue)
이 정도면 변환할 수 있습니다.float로.Int
플로트 값을 다음 위치에 저장한다고 가정합니다."X"정수값을 저장합니다."Y".
Var Y = Int(x);
또는
var myIntValue = Int(myFloatValue)
var i = 1 as Int
var cgf = CGFLoat(i)
여기에 제시된 솔루션의 대부분은 큰 값으로 인해 크래시되므로 프로덕션 코드에서 사용하지 마십시오.
큰 이 코드를 를 고정합니다.Double/최소/최소Int★★★★★★ 。
let bigFloat = Float.greatestFiniteMagnitude
let smallFloat = -bigFloat
extension Float {
func toIntTruncated() -> Int {
let maxTruncated = min(self, Float(Int.max).nextDown)
let bothTruncated = max(maxTruncated, Float(Int.min))
return Int(bothTruncated)
}
}
// This crashes:
// let bigInt = Int(bigFloat)
// this works for values up to 9223371487098961920
let bigInt = bigFloat.toIntTruncated()
let smallInt = smallFloat.toIntTruncated()
계산된 속성을 사용하여 편리한 확장을 만들고 프로젝트의 모든 위치에서 사용할 수 있습니다.
extension Float{
var toInt : Int{
return Int(self)
}
}
부르기
private var call: Float = 55.9
print(call.toInt)
Int64IntInt64int int int int at inda.
언급URL : https://stackoverflow.com/questions/24029917/convert-float-to-int-in-swift
'programing' 카테고리의 다른 글
| SQL Server 데이터베이스에서 UTF-8 대조 사용 방법 (0) | 2023.04.21 |
|---|---|
| ASP.NET에서는 세션을 언제 사용해야 합니까?세션이 아닌 클리어()입니다.포기()? (0) | 2023.04.21 |
| Azure 함수 앱 로그가 표시되지 않음 (0) | 2023.04.21 |
| 명령 프롬프트에서 .exe를 실행하는 Bat 파일 (0) | 2023.04.21 |
| bash에서는 어떻게 전류 입력을 클리어합니까? (0) | 2023.04.21 |