NumberFormatter.swift 1.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748
  1. //
  2. // NSNumberFormatter.swift
  3. // Loop
  4. //
  5. // Created by Nate Racklyeft on 9/5/16.
  6. // Copyright © 2016 Nathan Racklyeft. All rights reserved.
  7. //
  8. import Foundation
  9. import HealthKit
  10. extension NumberFormatter {
  11. func string(from number: Double) -> String? {
  12. return string(from: NSNumber(value: number))
  13. }
  14. func string(from number: Double, unit: String, style: Formatter.UnitStyle = .medium) -> String? {
  15. guard let stringValue = string(from: number) else {
  16. return nil
  17. }
  18. let format: String
  19. switch style {
  20. case .long, .medium:
  21. format = LocalizedString(
  22. "quantity-and-unit-space",
  23. value: "%1$@ %2$@",
  24. comment: "Format string for combining localized numeric value and unit with a space. (1: numeric value)(2: unit)"
  25. )
  26. case .short:
  27. fallthrough
  28. @unknown default:
  29. format = LocalizedString(
  30. "quantity-and-unit-tight",
  31. value: "%1$@%2$@",
  32. comment: "Format string for combining localized numeric value and unit without spacing. (1: numeric value)(2: unit)"
  33. )
  34. }
  35. return String(
  36. format: format,
  37. stringValue,
  38. unit
  39. )
  40. }
  41. }