Created
November 18, 2015 17:36
-
-
Save erica/bc0e0fba6887142e5a0f to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/* | |
erica sadun ericasadun.com | |
Math Types | |
Swift2 | |
*/ | |
import Foundation | |
import QuartzCore | |
// MARK: Conversion | |
//: Numbers that can be represented as Double instances | |
public protocol DoubleRepresentable { | |
var doubleValue: Double {get} | |
} | |
//: Numbers that convert to other types | |
public protocol ConvertibleNumberType: DoubleRepresentable { | |
var floatValue: Float { get } | |
var intValue: Int { get } | |
var CGFloatValue: CGFloat { get } | |
} | |
// Default conversion implementation | |
public extension ConvertibleNumberType { | |
public var floatValue: Float {get {return Float(doubleValue)}} | |
public var intValue: Int {get {return lrint(doubleValue)}} | |
public var CGFloatValue: CGFloat {get {return CGFloat(doubleValue)}} | |
} | |
extension Double: ConvertibleNumberType {public var doubleValue: Double {return self}} | |
extension Int: ConvertibleNumberType {public var doubleValue: Double {return Double(self)}} | |
extension CGFloat: ConvertibleNumberType {public var doubleValue: Double {return Double(self)}} | |
extension Float: ConvertibleNumberType {public var doubleValue: Double {return Double(self)}} | |
public extension ConvertibleNumberType { | |
public func toPrecision(digits: Int) -> String { | |
if digits == 0 {return "\(lrint(self.doubleValue))"} | |
let factor = pow(10.0, Double(digits)) | |
let trunc = round(doubleValue * factor) / factor | |
var result = "\(trunc)" | |
while result.rangeOfString(".")?.startIndex.distanceTo(result.endIndex) < (digits + 1) { | |
result += "0" | |
} | |
return result | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment