12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273 |
- //
- // BFNumber+Ext.swift
- // PQSpeed
- //
- // Created by SanW on 2020/7/20.
- // Copyright © 2020 BytesFlow. All rights reserved.
- //
- import Foundation
- public extension Int {
- /// 分数字格式化如413200->4,132.09
- /// 是否保留2位小数
- /// - Parameter isDecimal: <#isDecimal description#>
- /// - Returns: <#description#>
- func paraseDecimalFormatterValue(isDecimal: Bool = false) -> String? {
- let decimal = self % 100
- let nonDecimal = self / 100
- let formatter = NumberFormatter()
- formatter.numberStyle = .decimal
- if let title = formatter.string(from: NSNumber(value: nonDecimal)) {
- if isDecimal {
- return title + String(format: ".%02d", decimal)
- } else {
- return title
- }
- }
- return nil
- }
- /// 改变单位为万
- /// @param originUnit <#originUnit description#>
- func changeUnit() -> String {
- var unitStr: String = ""
- if self < 10000 {
- unitStr = "\(self)"
- } else if self <= 1_000_000 {
- let divisor = pow(10.0, Double(1))
- let decimal = ((Double(self) / 10000) * divisor).rounded() / divisor
- unitStr = "\(decimal)万"
- } else {
- unitStr = "\(self / 10000)万"
- }
- return unitStr
- }
- }
- // MARK: - Float double类型扩展
- extension Float {
- /// 准确的小数尾截取 - 没有进位
- /*
- // 11.999003 -> 12.0
- var pp = 11.999003
- String(format: "%.1f", pp) 这个方法会进行四舍五入
- */
- public func decimalString(_ base: Self = 1) -> String {
- return "\(self.decimalNumber(base))"
- }
- public func decimalNumber(_ base: Self = 1) -> Float {
- let tempCount: Self = pow(10, base)
- let temp = self*tempCount
-
- let target = Self(Int(temp))
- let stepone = target/tempCount
- if stepone.truncatingRemainder(dividingBy: 1) == 0 {
- return Float(String(format: "%.0f", stepone)) ?? 0.0
- }else{
- return stepone
- }
- }
- }
|