在 iOS 中取得系統版本可透過 UIDevice 的 systemVersion 屬性,結果通常是像 7.1.1 的字串。
若直接轉成 float,遇到三段版本號時容易出現精度問題,例如 7.1.1 可能變成 7.0899999999999,後續做版本比較時容易出錯。
較穩妥的做法是自行整理版本字串:先移除小數點,再把第一個小數點放回適當位置,最後轉成數值。這樣可保留主要版本與次版本的可讀性,也能避免浮點數轉換造成的誤差。
+ (CGFloat)systemVersion {
NSString *sVersion = [[UIDevice currentDevice] systemVersion];
NSRange fRange = [sVersion rangeOfString:@"."];
CGFloat version = 0.0f;
if (fRange.location != NSNotFound) {
sVersion = [sVersion stringByReplacingOccurrencesOfString:@"." withString:@""];
NSMutableString *mVersion = [NSMutableString stringWithString:sVersion];
[mVersion insertString:@"." atIndex:fRange.location];
version = [mVersion floatValue];
} else {
version = [sVersion floatValue];
}
return version;
}
若需要更精確的版本判斷,建議改用字串比較或將版本拆成整數陣列,而不是依賴浮點數。