forked from LoopKit/LoopKit
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathNumberFormatter.swift
More file actions
49 lines (41 loc) · 1.36 KB
/
NumberFormatter.swift
File metadata and controls
49 lines (41 loc) · 1.36 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
//
// NSNumberFormatter.swift
// Loop
//
// Created by Nate Racklyeft on 9/5/16.
// Copyright © 2016 Nathan Racklyeft. All rights reserved.
//
import Foundation
import HealthKit
extension NumberFormatter {
func string(from number: Double) -> String? {
return string(from: NSNumber(value: number))
}
func string(from number: Double, unit: String, style: Formatter.UnitStyle = .medium, avoidLineBreaking: Bool = true) -> String? {
guard let stringValue = string(from: number) else {
return nil
}
let separator: String
switch style {
case .long:
separator = " "
case .medium:
separator = avoidLineBreaking ? .nonBreakingSpace : " "
case .short:
fallthrough
@unknown default:
separator = avoidLineBreaking ? .wordJoiner : ""
}
let unit = avoidLineBreaking ? unit.replacingOccurrences(of: "/", with: "\(String.wordJoiner)/\(String.wordJoiner)") : unit
return String(
format: LocalizedString("%1$@%2$@%3$@", comment: "String format for value with units (1: value, 2: separator, 3: units)"),
stringValue,
separator,
unit
)
}
}
public extension String {
static let nonBreakingSpace = "\u{00a0}"
static let wordJoiner = "\u{2060}"
}