iOS中一个很重要,但是不熟悉的类NumberFormatter(上)

本文基于Swift3.0.1,Xcode8.1,模拟器英文环境

Demo

如果你和我一样,在一家金融公司“搬砖”。在项目中,难免你需要处理很多种数字格式。
例如:

1234567

格式名 数字
序数形式 1,234,567th
货币形式 USD1,234,567
会计计数 $1,234,567
科学计数 1.234567E6
朗读形式 one million two hundred thirty-four thousand five hundred sixty-seven
货币形式 $1,234,567.00
百分数形式 123,456,700%
货币形式 1,234,567.00 US dollars

如果单独处理一种情况,或者两种情况,我想机智的你,封装一个工具方法应该不是问题。但是,通常上面的格式都是在NSNumberString相互转换,有时可能你需要进位,需要抹零,取整,小数点后面保留1位小数点后面保留2位。。。
如果再加上四则运算,我想你肯定有点恼了,当然办法总是比困难的,也许你之前的处理办法也很好。但是看完这篇文章之后,我相信你肯定会回去优化你之前的方法。

音乐响起,主角出场。。。

NumberFormatter(NSNumberFormatter)

numberStyle

          NumberFormatter.Style.none,
          NumberFormatter.Style.decimal,
          NumberFormatter.Style.currency,
          NumberFormatter.Style.percent,
          NumberFormatter.Style.scientific,
          NumberFormatter.Style.spellOut,
          NumberFormatter.Style.ordinal, 
          NumberFormatter.Style.currencyISOCode,
          NumberFormatter.Style.currencyPlural,  
          NumberFormatter.Style.currencyAccounting

这是一个枚举类型的属性,对一串数字字符串格式化后的结果就是大概是上面那张表,在Demo中有详细的内容输出,这里不赘述。

locale

        let formatter = NumberFormatter()
        print(formatter.locale)  // en_US (current)
        formatter.locale = Locale(identifier: "fr_FR")
        print(formatter.currencySymbol) // €
        formatter.locale = Locale(identifier: "en_US")
        print(formatter.currencySymbol) // $

这个属性的主要作用是决定货币符号,货币代码货币阅读方式输出

generatesDecimalNumbers

    /*
     * default: false
     * desc:  控制这个func number(from string: String) -> NSNumber?的返回值是
     *        false是NSNumber
     *        true是NSDecimalNumber
     */
    
    // open var generatesDecimalNumbers: Bool
    func generatesDecimalNumbers() {
        let numberFormatter = NumberFormatter()
        numberFormatter.generatesDecimalNumbers = true
        let str = numberFormatter.number(from: "1234.56878")
        if str!.isMember(of: NSNumber.self) {
            print("number")
        } else if str!.isMember(of: NSDecimalNumber.self) {
            print("DecimalNumber")
        }
    }

formatterBehavior

   /*
     *  default: Behavior
     *  desc: ??? 接收器的格式化器行为。
     */
    
    // open var formatterBehavior: NumberFormatter.Behavior
    func formatterBehavior() {
        let formatter = NumberFormatter()
        print(formatter.formatterBehavior)
    }

这个属性我没有找到相关的资料,凡是有这个???记号的都是我不知道具体用法的。

negativeFormat

    /*
     *  default: #
     *  desc: 负数的格式,有点类似时间格式化
     */
    
    // open var negativeFormat: String!
    func negativeFormat() {
        let formatter = NumberFormatter()
        print(formatter.negativeFormat)
        formatter.numberStyle = NumberFormatter.Style.currency
        print(formatter.string(from: -70.00)!) // -$70.00
        formatter.negativeFormat = "¤-#,##0.00"
        print(formatter.string(from: -70.00)!) //$-70.00
    }

textAttributesForNegativeValues

    /*
     *  default: nil
     *  desc: ???  用于显示负值的文本属性。
     */
    
    // open var textAttributesForNegativeValues: [String : Any]?
    func textAttributesForNegativeValues() {
        let formatter = NumberFormatter()
        print(formatter.textAttributesForNegativeValues as Any)
    }

positiveFormat

    /*
     *  default: #
     *  desc: 正数的格式,有点类似时间格式化
     */
    
    // open var positiveFormat: String!
    func positiveFormat() {
        let formatter = NumberFormatter()
        print(formatter.positiveFormat)
        formatter.numberStyle = NumberFormatter.Style.currency
        print(formatter.string(from: 70.00)!) // $70.00
        formatter.positiveFormat = "+¤#,##0.00"
        print(formatter.string(from: 70.00)!) //+$70.00
    }

textAttributesForPositiveValues

    /*
     *  default: nil
     *  desc: ??? 用于显示正值的文本属性。
     */
    
    // open var textAttributesForPositiveValues: [String : Any]?
    func textAttributesForPositiveValues() {
        let formatter = NumberFormatter()
        print(formatter.textAttributesForPositiveValues as Any)
    }

allowsFloats

/* 
 *  default: true
 *  desc: 是否允许浮点数
 */

// open var allowsFloats: Bool
func allowsFloats() {
    let formatter = NumberFormatter()
    let str = formatter.number(from: "1237868794.56878")
    print(str!) // 1237868794.56878
    formatter.allowsFloats = false
    let str1 = formatter.number(from: "1237868794.56878")
    print(str1 as Any) // nil
}

decimalSeparator

func decimalSeparator() {
        let formatter = NumberFormatter()
        formatter.numberStyle = NumberFormatter.Style.decimal
        print(formatter.decimalSeparator)
        formatter.decimalSeparator = ","
        let str = formatter.number(from: "1237868,79456878")
        print(str!) // 1237868.79456878
    }

alwaysShowsDecimalSeparator

    /*
     *  default: false
     *  desc: 确定接收器是否始终显示小数分隔符,即使对于整数也是如此。
     */
    
    // open var alwaysShowsDecimalSeparator: Bool
    func alwaysShowsDecimalSeparator() {
        let formatter = NumberFormatter()
        formatter.numberStyle = NumberFormatter.Style.decimal
        print(formatter.alwaysShowsDecimalSeparator)
        formatter.alwaysShowsDecimalSeparator = true
        let str = formatter.string(from: 14321423)
        print(str!) // 14,321,423.
    }

currencyDecimalSeparator

    /*
     *  default: '.'
     *  desc: 小数点替代符
     */
    
    // open var currencyDecimalSeparator: String!
    func currencyDecimalSeparator() {
        let formatter = NumberFormatter()
        formatter.numberStyle = NumberFormatter.Style.currency
        print(formatter.currencyDecimalSeparator)
        let str = formatter.string(from: 14321423.123)
        print(str!) //  $14,321,423.12
        formatter.currencyDecimalSeparator = "_"
        let str1 = formatter.string(from: 14321423.123)
        print(str1!) // $14,321,423_12
    }

usesGroupingSeparator

    /*
     *  default: true
     *  desc: 是否使用分隔符
     */
    
    // open var usesGroupingSeparator: Bool
    func usesGroupingSeparator() {
        let formatter = NumberFormatter()
        formatter.numberStyle = NumberFormatter.Style.currency
        print(formatter.usesGroupingSeparator)
        let str = formatter.string(from: 14321423.123)
        print(str!) //  $14,321,423.12
        formatter.usesGroupingSeparator = false
        let str1 = formatter.string(from: 14321423.123)
        print(str1!) // $14321423.12
    }

groupingSeparator

    /*
     *  default: ','
     *  desc:  NumberFormatter.Style.decimal 的分隔符
     */
    
    // open var groupingSeparator: String!
    func groupingSeparator() {
        let formatter = NumberFormatter()
        formatter.numberStyle = NumberFormatter.Style.decimal
        print(formatter.groupingSeparator)
        let str = formatter.string(from: 14321423.123)
        print(str!) //  $14,321,423.123
        formatter.groupingSeparator = "*"
        let str1 = formatter.string(from: 14321423.123)
        print(str1!) // $14*321*423.123
    }

zeroSymbol

    /*
     *  default: nil
     *  desc: 数字0的替换符号
     */
    
    // open var zeroSymbol: String?
    func zeroSymbol() {
        let formatter = NumberFormatter()
        formatter.numberStyle = NumberFormatter.Style.decimal
        print(formatter.zeroSymbol as Any)
        let str = formatter.string(from: 0)
        print(str!) //  0
        formatter.zeroSymbol = "*"
        let str1 = formatter.string(from: 0)
        print(str1!) // *
    }

textAttributesForZero

    /*
     *  default: nil
     *  desc: ??? 接收器用于显示零值的属性字符串。
     */
    
    // open var textAttributesForZero: [String : Any]?
    func textAttributesForZero() {
        let formatter = NumberFormatter()
        print(formatter.textAttributesForZero as Any)
    }

nilSymbol

    /*
     *  default: nil
     *  desc: ??? 接收器用来表示空值的字符串。
     */
    
    // open var nilSymbol: String
    func nilSymbol() {
        let formatter = NumberFormatter()
        formatter.numberStyle = NumberFormatter.Style.decimal
        print(formatter.nilSymbol)
        formatter.nilSymbol = ">"
        let str = formatter.number(from: "--")
        print(str as Any)
    }

textAttributesForNil

/*
 *  default: nil
 *  desc: ??? 用于显示nil符号的文本属性。
 */

// open var textAttributesForNil: [String : Any]?
func textAttributesForNil() {
    
    let formatter = NumberFormatter()
    formatter.numberStyle = NumberFormatter.Style.decimal
    print(formatter.textAttributesForNil as Any)
}

notANumberSymbol

    /*
     *  default: NaN
     *  desc: ??? 接收器用来表示NaN(“不是数字”)的字符串。 非数字符号 "NaN"
     */
    
    // open var notANumberSymbol: String!
    
    func notANumberSymbol() {
        let formatter = NumberFormatter()
        formatter.numberStyle = NumberFormatter.Style.decimal
        print(formatter.notANumberSymbol)
    }

关于NaN

textAttributesForNotANumber

    /*
     *  default: nil
     *  desc: ??? 用于显示NaN(“不是数字”)字符串的文本属性。
     */
    
    // open var textAttributesForNotANumber: [String : Any]?
    
    func textAttributesForNotANumber() {
        let formatter = NumberFormatter()
        formatter.numberStyle = NumberFormatter.Style.decimal
        print(formatter.textAttributesForNotANumber as Any)
    }

positiveInfinitySymbol

    /*
     *  default: +∞
     *  desc: 正无穷符号
     */
    
    // open var positiveInfinitySymbol: String
    func positiveInfinitySymbol() {
        let formatter = NumberFormatter()
        formatter.numberStyle = NumberFormatter.Style.decimal
        print(formatter.positiveInfinitySymbol)
    }

textAttributesForPositiveInfinity

    /*
     *  default: nil
     *  desc: ??? 用于显示正无穷大符号的文本属性。
     */
    
    // open var textAttributesForPositiveInfinity: [String : Any]?
    func textAttributesForPositiveInfinity() {
        let formatter = NumberFormatter()
        formatter.numberStyle = NumberFormatter.Style.decimal
        print(formatter.textAttributesForPositiveInfinity as Any)
    }

negativeInfinitySymbol

    /*
     *  default: -∞
     *  desc: 负无穷
     */
    
    // open var negativeInfinitySymbol: String
    func negativeInfinitySymbol() {
        let formatter = NumberFormatter()
        formatter.numberStyle = NumberFormatter.Style.decimal
        print(formatter.negativeInfinitySymbol)
    }

textAttributesForNegativeInfinity

    /*
     *  default: nil
     *  desc: ??? 用于显示负无穷大符号的文本属性。
     */
    
    // open var textAttributesForNegativeInfinity: [String : Any]?
    func textAttributesForNegativeInfinity() {
        let formatter = NumberFormatter()
        formatter.numberStyle = NumberFormatter.Style.decimal
        print(formatter.textAttributesForNegativeInfinity as Any)
    }

positivePrefix

    /*
     *  default: ''
     *  desc: 正数的前缀
     */
    
    // open var positivePrefix: String!
    
    func positivePrefix() {
        let formatter = NumberFormatter()
        print(formatter.positivePrefix, "😁")
        let str = formatter.string(from: 123456)
        print(str as Any)
        formatter.positivePrefix = "+" // 123456
        let str1 = formatter.string(from: 123456) // +123456
        print(str1 as Any)
    }

positiveSuffix

    /*
     *  default: ''
     *  desc: 正数的后缀
     */
    
    // open var positiveSuffix: String!
    func positiveSuffix() {
        let formatter = NumberFormatter()
        print(formatter.positiveSuffix, "😁")
        let str = formatter.string(from: 123456)
        print(str as Any) // "123456"
        formatter.positiveSuffix = "🌞"
        let str1 = formatter.string(from: 123456)
        print(str1 as Any) // "123456🌞"
    }

negativePrefix

    /*
     *  default: '-'
     *  desc: 负数的前缀
     */
    
    // open var negativePrefix: String!
    func negativePrefix() {
        let formatter = NumberFormatter()
        print(formatter.negativePrefix, "😁")
        let str = formatter.string(from: -123456)
        print(str as Any) // -123456
        formatter.negativePrefix = "减号"
        let str1 = formatter.string(from: -123456) // 减号123456
        print(str1 as Any)
    }

negativeSuffix

    /*
     *  default: '-'
     *  desc: 负数的后缀
     */
    
    // open var negativeSuffix: String!
    func negativeSuffix() {
        let formatter = NumberFormatter()
        print(formatter.negativeSuffix, "😁")
        let str = formatter.string(from: -123456)
        print(str as Any) // "-123456"
        formatter.negativeSuffix = "🌞"
        let str1 = formatter.string(from: -123456) // "-123456🌞"
        print(str1 as Any) //
    }

currencyCode

    /*
     *  default: USD (应该是根据系统语言变化的)
     *  desc: 货币代码
     */

    // open var currencyCode: String!
    func currencyCode() {
        let formatter = NumberFormatter()
        print(formatter.currencyCode)
    }

currencySymbol

    /*
     *  default: $(应该会随系统语言变化)
     *  desc: 货币符号
     */
    
    // open var currencySymbol: String!
    func currencySymbol() {
        let formatter = NumberFormatter()
        formatter.numberStyle = NumberFormatter.Style.currency
        print(formatter.currencySymbol)
        let str = formatter.string(from: 123456) 
        print(str as Any) // $123,456.00
        formatter.currencySymbol = "💵"
        let str1 = formatter.string(from: 123456) 
        print(str1 as Any) // 💵123,456.00
    }

internationalCurrencySymbol

    /*
     *  default: USD (会随语言变化而变化,设置locale也会变化)
     *  desc:
     */
    
    // open var internationalCurrencySymbol: String!
    func internationalCurrencySymbol() {
        let formatter = NumberFormatter()
        //        formatter.locale = Locale(identifier: "de_DE")
        formatter.numberStyle = NumberFormatter.Style.currency
        print(formatter.internationalCurrencySymbol)
        let str = formatter.string(from: 123456)
        print(str as Any)
        let str1 = formatter.string(from: 123456)
        print(str1 as Any)
    }

percentSymbol

    /*
     *  default: %
     *  desc: 百分号,可以自定义
     */
    
    // open var percentSymbol: String!
    func percentSymbol() {
        let formatter = NumberFormatter()
        formatter.numberStyle = NumberFormatter.Style.percent
        print(formatter.percentSymbol)
        let str = formatter.string(from: 123456) // 12,345,600%
        print(str as Any)
        formatter.percentSymbol = "😄"
        let str1 = formatter.string(from: 123456) // 12,345,600😄
        print(str1 as Any)
    }

perMillSymbol

    /*
     *  default: ‰
     *  desc: 千分号
     */
    
    // open var perMillSymbol: String!
    func perMillSymbol() {
        let formatter = NumberFormatter()
        formatter.numberStyle = NumberFormatter.Style.percent
        print(formatter.perMillSymbol)
    }

minusSign

    /*
     *  default: -
     *  desc: 减号
     */
    
    //  open var minusSign: String!
    func minusSign() {
        let formatter = NumberFormatter()
        print(formatter.minusSign)
    }

plusSign

    /*
     *  default: +
     *  desc: 加号
     */
    
    // open var plusSign: String!
    func plusSign() {
        let formatter = NumberFormatter()
        print(formatter.plusSign)
    }

exponentSymbol

    /*
     *  default: E
     *  desc: 指数符号
     */
    
    // open var exponentSymbol: String!
    func exponentSymbol() {
        let formatter = NumberFormatter()
        print(formatter.exponentSymbol)
    } 

groupingSize

    /*
     *  default: 3
     *  desc: 数字分割的尺寸
     */
    
    // open var groupingSize: Int
    func groupingSize() {
        
        let formatter = NumberFormatter()
        formatter.numberStyle = NumberFormatter.Style.currency
        print(formatter.groupingSize)
        let str = formatter.string(from: 123456) // $123,456.00
        print(str as Any)
        formatter.groupingSize = 1
        let str1 = formatter.string(from: 123456) // $1,2,3,4,5,6.00
        print(str1 as Any)
    }

secondaryGroupingSize

    /*
     *  default: 0
     *  desc: 除了groupingSize决定的尺寸外,其他数字位分割的尺寸
     */
    
    // open var secondaryGroupingSize: Int
    func secondaryGroupingSize() {
        let formatter = NumberFormatter()
        formatter.numberStyle = NumberFormatter.Style.currency
        print(formatter.secondaryGroupingSize)
        let str = formatter.string(from: 123456) // $123,456.00
        print(str as Any)
        formatter.secondaryGroupingSize = 1
        let str1 = formatter.string(from: 123456) // $1,2,3,456.00
        print(str1 as Any)
    }

multiplier

    /*
     *  default: nil
     *  desc: 乘数
     */
    
    // @NSCopying open var multiplier: NSNumber?
    func multiplier() {
        let formatter = NumberFormatter()
        formatter.numberStyle = NumberFormatter.Style.currency
        print(formatter.multiplier as Any)
        let str = formatter.string(from: 123456) // $123,456.00
        print(str as Any)
        formatter.multiplier = 10
        let str1 = formatter.string(from: 123456) // $1,234,560.00
        print(str1 as Any)
    }

formatWidth

    /*
     *  default: 0
     *  desc: 格式化宽度(字符串所有字符个数)
     */
    
    // open var formatWidth: Int
    func formatWidth() {
        let formatter = NumberFormatter()
        formatter.numberStyle = NumberFormatter.Style.currency
        print(formatter.formatWidth)
        let str = formatter.string(from: 123456) // "$123,456.00"
        print(str as Any)
        formatter.formatWidth = 15
        let str1 = formatter.string(from: 123456) // "    $123,456.00"
        print(str1 as Any)
    }

paddingCharacter

    /*
     *  default: ''
     *  desc: 填充符号
     */
    
    // open var paddingCharacter: String!
    
    func paddingCharacter() {
        let formatter = NumberFormatter()
        formatter.numberStyle = NumberFormatter.Style.currency
        print(formatter.paddingCharacter)
        let str = formatter.string(from: 123456) // "$123,456.00"
        print(str as Any)
        formatter.formatWidth = 15
        formatter.paddingCharacter = "*"
        let str1 = formatter.string(from: 123456) // "****$123,456.00"
        print(str1 as Any)
    }

beforePrefix

    /*
     *  default: beforePrefix
     *  desc: 填充方向
     */
    
    // open var paddingPosition: NumberFormatter.PadPosition
    func paddingPosition() {
        let formatter = NumberFormatter()
        formatter.numberStyle = NumberFormatter.Style.currency
        print(formatter.paddingPosition == .beforePrefix)
        formatter.formatWidth = 15
        formatter.paddingCharacter = "*"
        let str = formatter.string(from: 123456) // "****$123,456.00"
        print(str as Any)
        formatter.paddingPosition = NumberFormatter.PadPosition.afterPrefix
        let str1 = formatter.string(from: 123456) // "$****123,456.00"
        print(str1 as Any)
    }

roundingMode

    /*
     *  default: halfEven
     *  desc: 舍入方式
     */
    
    // open var roundingMode: NumberFormatter.RoundingMode
    func roundingMode() {
        let formatter = NumberFormatter()
        formatter.numberStyle = NumberFormatter.Style.decimal
        print(formatter.roundingMode == .halfEven)
        let str = formatter.string(from: 123456.1235) // "123,456.124"
        print(str as Any)
        formatter.roundingMode = .halfDown
        let str1 = formatter.string(from: 123456.1235) // "123,456.123"
        print(str1 as Any)
    }

roundingIncrement

    /*
     *  default: 0
     *  desc: 保留到哪位小数
     */
    
    // @NSCopying open var roundingIncrement: NSNumber!
    func roundingIncrement() {
        let formatter = NumberFormatter()
        formatter.numberStyle = NumberFormatter.Style.decimal
        print(formatter.roundingIncrement)
        let str = formatter.string(from: 123456.1235) // "123,456.124"
        print(str as Any)
        formatter.roundingIncrement = 0.1
        let str1 = formatter.string(from: 123456.1235) // "123,456.1"
        print(str1 as Any)
    }

minimumIntegerDigits

    /*
     *  default: 1
     *  desc: 整数最少位数
     */
    // open var minimumIntegerDigits: Int
    func minimumIntegerDigits() {
        let formatter = NumberFormatter()
        formatter.numberStyle = NumberFormatter.Style.decimal
        print(formatter.minimumIntegerDigits)
        let str = formatter.string(from: 123456.1235) // "123,456.124"
        print(str as Any)
        formatter.minimumIntegerDigits = 10
        let str1 = formatter.string(from: 123456.1235) // "0,000,123,456.124"
        print(str1 as Any)
    }

maximumIntegerDigits

    /*
     *  default: 2000000000
     *  desc: 整数最多位数
     */
    
    // open var maximumIntegerDigits: Int
    func maximumIntegerDigits() {
        let formatter = NumberFormatter()
        formatter.numberStyle = NumberFormatter.Style.decimal
        print(formatter.maximumIntegerDigits)
        let str = formatter.string(from: 123456.1235) // "123,456.124"
        print(str as Any)
        formatter.maximumIntegerDigits = 1
        let str1 = formatter.string(from: 123456.1235) // "6.124"
        print(str1 as Any)
    }

minimumFractionDigits

    /*
     *  default: 0
     *  desc: 小数最少位数
     */
    
    // open var minimumFractionDigits: Int
    func minimumFractionDigits() {
        let formatter = NumberFormatter()
        formatter.numberStyle = NumberFormatter.Style.decimal
        print(formatter.minimumFractionDigits)
        let str = formatter.string(from: 123456.1235) // "123,456.124"
        print(str as Any)
        formatter.minimumFractionDigits = 10
        let str1 = formatter.string(from: 123456.1235) // "123,456.1235000000"
        print(str1 as Any)
    }

maximumFractionDigits

    /*
     *  default: 3 会根据numberStyle的值变化
     *  desc: 小数最多位数
     */
    
    // open var maximumFractionDigits: Int
    func maximumFractionDigits() {
        let formatter = NumberFormatter()
        formatter.numberStyle = NumberFormatter.Style.decimal
        print(formatter.maximumFractionDigits)
        let str = formatter.string(from: 123456.1235) // "123,456.124"
        print(str as Any)
        formatter.maximumFractionDigits = 1
        let str1 = formatter.string(from: 123456.1235) // "123,456.1"
        print(str1 as Any)
    }

minimum

    /*
     *  default: nil
     *  desc: ??? 接收器允许输入的最小数字。
     */
    
    // @NSCopying open var minimum: NSNumber?
    
    func minimum() {
        let formatter = NumberFormatter()
        formatter.numberStyle = NumberFormatter.Style.decimal
        print(formatter.minimum as Any)
    }

maximum

    /*
     *  default: nil
     *  desc: ??? 接收器允许输入的最大数字。
     */
    
    // @NSCopying open var maximum: NSNumber?
    func maximum() {
        let formatter = NumberFormatter()
        formatter.numberStyle = NumberFormatter.Style.decimal
        print(formatter.maximum as Any)
    }

currencyGroupingSeparator

    /*
     *  default: ','
     *  desc: 货币格式分隔符
     */
    
    // open var currencyGroupingSeparator: String!
    func currencyGroupingSeparator() {
        let formatter = NumberFormatter()
        formatter.numberStyle = NumberFormatter.Style.currency
        print(formatter.currencyGroupingSeparator as Any)
        let str = formatter.string(from: 123456.1235) // "$123,456.12"
        print(str as Any)
        formatter.currencyGroupingSeparator = "*"
        let str1 = formatter.string(from: 123456.1235) // "$123*456.12"
        print(str1 as Any)
    }

isLenient

    /*
     *  default: false
     *  desc: ??? 确定接收器是否将使用启发式来猜测字符串意图的数字。
     */
    
    // open var isLenient: Bool
    func isLenient() {
        let formatter = NumberFormatter()
        print(formatter.isLenient)
    }

usesSignificantDigits

    /*
     *  default: false
     *  desc: 是否使用有效数字
     */
    
    // open var usesSignificantDigits: Bool
    func usesSignificantDigits() {
        let formatter = NumberFormatter()
        formatter.numberStyle = NumberFormatter.Style.currency
        print(formatter.usesSignificantDigits)
        let str = formatter.string(from: 123456.1235) // "$123,456.12"
        print(str as Any)
        formatter.usesSignificantDigits = true
        let str1 = formatter.string(from: 123456.1235) // "$123,456"
        print(str1 as Any)
    }

minimumSignificantDigits

    /*
     *  default: 1
     *  desc: 最小有效数字位数
     */
    
    // open var minimumSignificantDigits: Int
    func minimumSignificantDigits() {
        let formatter = NumberFormatter()
        formatter.numberStyle = NumberFormatter.Style.currency
        print(formatter.minimumSignificantDigits)
        let str = formatter.string(from: 123456.1235) // "$123,456.12"
        print(str as Any)
        formatter.minimumSignificantDigits = 10
        let str1 = formatter.string(from: 123456.1235) // "$123,456.1235"
        print(str1 as Any)
    }

maximumSignificantDigits

    /*
     *  default: 6
     *  desc: 最大有效数字位数
     */
    
    // open var maximumSignificantDigits: Int
    func maximumSignificantDigits() {
        let formatter = NumberFormatter()
        formatter.numberStyle = NumberFormatter.Style.currency
        print(formatter.maximumSignificantDigits)
        let str = formatter.string(from: 123456.1235) // "$123,456.12"
        print(str as Any)
        formatter.maximumSignificantDigits = 2
        let str1 = formatter.string(from: 123456.1235) // "$120,000"
        print(str1 as Any)
        formatter.maximumSignificantDigits = 3
        let str2 = formatter.string(from: 123456.1235) // "$123,000"
        print(str2 as Any)
    }

isPartialStringValidationEnabled

    /*
     *  default: false
     *  desc: ??? 确定是否为接收器启用部分字符串验证。
     */
    
    // open var isPartialStringValidationEnabled: Bool
    func isPartialStringValidationEnabled() {
        let formatter = NumberFormatter()
        print(formatter.isPartialStringValidationEnabled)
    }

使用
func number(from string: String) -> NSNumber?

func string(from number: NSNumber) -> String?
需要注意的问题

        let n: NSNumber = 12345.65748
        let formatter = NumberFormatter()
        
        print(formatter.number(from: n.description) as Any) // 12345.65748
        print(formatter.string(from: n) as Any) // 12346
        let n: NSNumber = 12345.65748
        let formatter = NumberFormatter()
        formatter.numberStyle = NumberFormatter.Style.decimal
        print(formatter.number(from: n.description) as Any) // 12345.65748
        print(formatter.string(from: n) as Any) // 12,345.657

暂且先不讨论分割符“,”就精度而言,肯定选择前者,但是特殊格式有要求需要就选后者。但是这种情况请注意

        let n: NSNumber = 12345.65748
        let formatter = NumberFormatter()
        formatter.numberStyle = NumberFormatter.Style.currency
        //  formatter.currencySymbol = "" 
        print(formatter.number(from: n.description) as Any) // nil
        print(formatter.string(from: n) as Any) // $12,345.66

这是怎么回事?
n.description改成formatter.currencySymbol + n.description试试。
或者放开注释那句,那么最后那个也没有了货币符号。

不知道你有没有注意我使用了description这个属性,
在NSNumber有一点小小的bug

从64.01开始,NSNumber(value: 64.01).description得到是这样
64.01000000000001”到“99.01”都是有bug的,范围可能不准确。

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 197,597评论 5 462
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 83,053评论 2 375
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 144,583评论 0 326
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 52,888评论 1 267
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 61,772评论 5 358
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 46,536评论 1 275
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 36,922评论 3 388
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 35,554评论 0 254
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 39,838评论 1 293
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 34,861评论 2 314
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 36,677评论 1 328
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 32,483评论 3 316
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 37,928评论 3 300
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 29,104评论 0 19
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 30,403评论 1 255
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 41,945评论 2 343
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 41,156评论 2 339

推荐阅读更多精彩内容

  • 国家电网公司企业标准(Q/GDW)- 面向对象的用电信息数据交换协议 - 报批稿:20170802 前言: 排版 ...
    庭说阅读 10,813评论 6 13
  • Spring Cloud为开发人员提供了快速构建分布式系统中一些常见模式的工具(例如配置管理,服务发现,断路器,智...
    卡卡罗2017阅读 134,528评论 18 139
  • 1、随机数 不需要随机数种子 arc4random()%N + begin:产生begin~begin+N的随机数...
    我是小胡胡分胡阅读 4,126评论 0 2
  • Hello !亲爱的,我是蓉蓉,是一个3岁孩子的宝妈,也是付爱宝的内蒙古总代,加入付爱宝一年多的时间,我在呼和浩特...
    rr蓉蓉阅读 262评论 0 0
  • 文/清心图/网络 当爱只剩下伤害的时候,不如放手,成全。 “你知道吗?他死了。” 金兰说这话时,我和她刚刚在纪念碑...
    李清心1314阅读 868评论 6 13