Skip to content

Instantly share code, notes, and snippets.

@rayfix
Last active April 23, 2019 16:04
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save rayfix/3546fe68a62bc50e1abecdf2413d7b41 to your computer and use it in GitHub Desktop.
Save rayfix/3546fe68a62bc50e1abecdf2413d7b41 to your computer and use it in GitHub Desktop.
Scientific Notation
import Foundation
extension String.StringInterpolation {
private static let toSuper: [Character: String] = ["0": "\u{2070}",
"1": "\u{00B9}",
"2": "\u{00B2}",
"3": "\u{00B3}",
"4": "\u{2074}",
"5": "\u{2075}",
"6": "\u{2076}",
"7": "\u{2077}",
"8": "\u{2078}",
"9": "\u{2079}",
"-": "\u{207B}"]
mutating func appendInterpolation(superscript value: Int) {
let string = String(value)
let result = string.map {
String.StringInterpolation.toSuper[$0]!
}.joined()
appendInterpolation(result)
}
mutating func appendInterpolation<T: BinaryFloatingPoint>(_ value: T, precision: Int = 3) {
var result = String(describing: value)
defer {
appendInterpolation(result)
}
guard precision > 0 else {
return
}
let string = String(describing: value)
guard let index = string.firstIndex(of: ".") else {
return
}
let offset = precision+1
let last = string.index(index, offsetBy: offset,
limitedBy: string.endIndex) ?? string.endIndex
result = String(string[..<last])
let fraction = string[index..<last].count
if fraction < offset {
result += String(repeating: "0", count: offset-fraction)
}
}
mutating func appendInterpolation<T: BinaryFloatingPoint>(scientific value: T,
precision: Int = 3) {
guard value != 0 else {
appendLiteral("0")
return
}
let exponentFloat = log10(Double(value.magnitude)).rounded(.down)
let lead = Double(value) / pow(10.0, exponentFloat)
let exponent = Int(exponentFloat)
appendInterpolation(lead, precision: precision)
appendLiteral("×10")
appendInterpolation(superscript: exponent)
}
}
print("This is a test of \(scientific: 6.02e23, precision: 3)")
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment