Newer Older
49 lines | 1.092kb
Bogdan Timofte authored 2 weeks ago
1
//
2
//  Double.swift
3
//  USB Meter
4
//
5
//  Created by Bogdan Timofte on 08/03/2020.
6
//  Copyright © 2020 Bogdan Timofte. All rights reserved.
7
//
8

            
9
import Foundation
10
import CoreGraphics
11

            
12
extension Double {
13

            
14
    func format(f: String) -> String {
15
        return String(format: "%\(f)", self)
16
    }
17

            
18
    func format(decimalDigits: Int) -> String {
19
        return String(format: "%.\(decimalDigits)f", self)
20
    }
21

            
22
    func format(digits: Int) -> String {
23
        for d in 0...digits {
24
            if self < pow(10, d).doubleValue {
25
                return self.format(f: ".\(digits - d)f")
26
            }
27
        }
28
        return self.format(f: ".0f")
29
    }
30

            
31
    var uInt8Value: UInt8 {
32
        return UInt8(self)
33
    }
34

            
35
    var intValue: Int {
36
        return Int(self)
37
    }
38

            
39
    var CGFloatValue: CGFloat {
40
        return CGFloat(self)
41
    }
42

            
43
    func format(fractionDigits: Int) ->String {
44
        let nf = NumberFormatter()
45
        nf.minimumFractionDigits = fractionDigits
46
        nf.maximumFractionDigits = fractionDigits
47
        return nf.string(from: NSNumber(value: self))!
48
    }
49
}