-
基礎知識
Double的精度為十五個十進制有效數字,
Float的精度為六個十進制有效數字。
兩者都需要擴展后實現保留幾位有效小數的操作,擴展方法需要在classViewController外層增加。
-
代碼:
import UIKit
class ViewController: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
let n1 : Float = 32.141592654
let n2 : Double = 3.141592654
print(n1)
print(n2)
print(n2.format(".3"))
// Do any additional setup after loading the view, typically from a nib. }
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
}
//擴展
extension Double {
func format(f : String) -> String {
return NSString.init(format: "%\(f)f", self) as String
}
}