Double,Float浮点类型用扩展限制小数点后位数

  • 基础知识

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    
    }
}

你可能感兴趣的:(Double,Float浮点类型用扩展限制小数点后位数)