BFNumber+Ext.swift 2.1 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273
  1. //
  2. // BFNumber+Ext.swift
  3. // PQSpeed
  4. //
  5. // Created by SanW on 2020/7/20.
  6. // Copyright © 2020 BytesFlow. All rights reserved.
  7. //
  8. import Foundation
  9. public extension Int {
  10. /// 分数字格式化如413200->4,132.09
  11. /// 是否保留2位小数
  12. /// - Parameter isDecimal: <#isDecimal description#>
  13. /// - Returns: <#description#>
  14. func paraseDecimalFormatterValue(isDecimal: Bool = false) -> String? {
  15. let decimal = self % 100
  16. let nonDecimal = self / 100
  17. let formatter = NumberFormatter()
  18. formatter.numberStyle = .decimal
  19. if let title = formatter.string(from: NSNumber(value: nonDecimal)) {
  20. if isDecimal {
  21. return title + String(format: ".%02d", decimal)
  22. } else {
  23. return title
  24. }
  25. }
  26. return nil
  27. }
  28. /// 改变单位为万
  29. /// @param originUnit <#originUnit description#>
  30. func changeUnit() -> String {
  31. var unitStr: String = ""
  32. if self < 10000 {
  33. unitStr = "\(self)"
  34. } else if self <= 1_000_000 {
  35. let divisor = pow(10.0, Double(1))
  36. let decimal = ((Double(self) / 10000) * divisor).rounded() / divisor
  37. unitStr = "\(decimal)万"
  38. } else {
  39. unitStr = "\(self / 10000)万"
  40. }
  41. return unitStr
  42. }
  43. }
  44. // MARK: - Float double类型扩展
  45. extension Float {
  46. /// 准确的小数尾截取 - 没有进位
  47. /*
  48. // 11.999003 -> 12.0
  49. var pp = 11.999003
  50. String(format: "%.1f", pp) 这个方法会进行四舍五入
  51. */
  52. public func decimalString(_ base: Self = 1) -> String {
  53. return "\(self.decimalNumber(base))"
  54. }
  55. public func decimalNumber(_ base: Self = 1) -> Float {
  56. let tempCount: Self = pow(10, base)
  57. let temp = self*tempCount
  58. let target = Self(Int(temp))
  59. let stepone = target/tempCount
  60. if stepone.truncatingRemainder(dividingBy: 1) == 0 {
  61. return Float(String(format: "%.0f", stepone)) ?? 0.0
  62. }else{
  63. return stepone
  64. }
  65. }
  66. }