LargeValueFormatter.swift 1.4 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758
  1. //
  2. // LargeValueFormatter.swift
  3. // ChartsDemo
  4. // Copyright © 2016 dcg. All rights reserved.
  5. //
  6. import Foundation
  7. import Charts
  8. private let MAX_LENGTH = 5
  9. @objc protocol Testing123 { }
  10. public class LargeValueFormatter: NSObject, ValueFormatter, AxisValueFormatter {
  11. /// Suffix to be appended after the values.
  12. ///
  13. /// **default**: suffix: ["", "k", "m", "b", "t"]
  14. public var suffix = ["", "k", "m", "b", "t"]
  15. /// An appendix text to be added at the end of the formatted value.
  16. public var appendix: String?
  17. public init(appendix: String? = nil) {
  18. self.appendix = appendix
  19. }
  20. fileprivate func format(value: Double) -> String {
  21. var sig = value
  22. var length = 0
  23. let maxLength = suffix.count - 1
  24. while sig >= 1000.0 && length < maxLength {
  25. sig /= 1000.0
  26. length += 1
  27. }
  28. var r = String(format: "%2.f", sig) + suffix[length]
  29. if let appendix = appendix {
  30. r += appendix
  31. }
  32. return r
  33. }
  34. public func stringForValue(_ value: Double, axis: AxisBase?) -> String {
  35. return format(value: value)
  36. }
  37. public func stringForValue(
  38. _ value: Double,
  39. entry: ChartDataEntry,
  40. dataSetIndex: Int,
  41. viewPortHandler: ViewPortHandler?) -> String {
  42. return format(value: value)
  43. }
  44. }