LargeValueFormatter.swift 1.5 KB

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