How to get the first two digits after the decimal point of a float number in Swift

1 Answer

0 votes
import Foundation

let f = 3486.716052
let s = String(f)

if let pointPos = s.firstIndex(of: ".") {
    let start = s.index(after: pointPos)
    let end = s.index(start, offsetBy: 2, limitedBy: s.endIndex) ?? s.endIndex
    
    print(s[start..<end])
}



/*
run:
   
71

*/

 



answered Oct 27, 2024 by avibootz
...