bgUnits.swift 1.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657
  1. //
  2. // Units.swift
  3. // LoopFollow
  4. //
  5. // Created by Jon Fawcett on 6/22/20.
  6. // Copyright © 2020 Jon Fawcett. All rights reserved.
  7. //
  8. import Foundation
  9. class bgUnits {
  10. static func toDisplayUnits(_ value: String) -> String {
  11. if UserDefaultsRepository.units.value == "mg/dL" {
  12. return removeDecimals(value)
  13. } else {
  14. // convert mg/dL to mmol/l
  15. let floatValue : Float = Float(value)! * 0.0555
  16. return String(floatValue.cleanValue)
  17. }
  18. }
  19. // if a "." is contained, simply takes the left part of the string only
  20. static func removeDecimals(_ value : String) -> String {
  21. if !value.contains(".") {
  22. return value
  23. }
  24. return String(value[..<value.firstIndex(of: ".")!])
  25. }
  26. static func removePeriodForBadge(_ value: String) -> String {
  27. return value.replacingOccurrences(of: ".", with: "")
  28. }
  29. }
  30. extension Float {
  31. // remove the decimal part of the float if it is ".0" and trim whitespaces
  32. var cleanValue: String {
  33. return self.truncatingRemainder(dividingBy: 1) == 0
  34. ? String(format: "%5.0f", self).trimmingCharacters(in: CharacterSet.whitespaces)
  35. : String(format: "%5.1f", self).trimmingCharacters(in: CharacterSet.whitespaces)
  36. }
  37. var roundTo3f: Float {
  38. return round(to: 3)
  39. }
  40. func round(to places: Int) -> Float {
  41. let divisor = pow(10.0, Float(places))
  42. return (divisor * self).rounded() / divisor
  43. }
  44. }