格式化Swift 3中的数字

时间:2017-06-19 12:34:07

标签: swift numbers nsnumberformatter

我想将数字格式化为:来自123234234234的123.234.234.234取决于用户在文本字段中键入的内容。 我不想管理货币,它不是关于货币,而是关于用户必须输入一个数字,这个数字应该正确格式化以便于阅读。

不带逗号,带点。

我在整个研究中发现只有货币的东西

8 个答案:

答案 0 :(得分:12)

您所寻找的内容可能是NumberFormatter

groupingSeparator
let formater = NumberFormatter()
formater.groupingSeparator = "."
formater.numberStyle = .decimal
let formattedNumber = formater.string(from: number)

答案 1 :(得分:6)

您可以使用let yourNumber = 123234234234 let numberFormatter = NumberFormatter() numberFormatter.numberStyle = NumberFormatter.Style.decimal numberFormatter.groupingSeparator = "." let formattedNumber = numberFormatter.string(from: NSNumber(value:yourNumber))

执行此操作
 fetch(data.defaults + 'returnSqlRes.php',
    {
        headers: {'Accept': 'application/json', 'Content-Type': 'application/json'},
        method: "post",
        body: JSON.stringify(data.sql)
    })
    .then(status)
    .then(json)
    .then(function (sData) {

        var dt={};
        dt['o']=data.tableId;
        dt['data']=sData;
        _.forEach(dt.data[0],function (row) {
            row.DT_RowId = composeId(data.pk, row);
            _.forEach( data.tableCols,function (o, index) {
                if (_.has(o, 'complexList')) {
                    var fieldName = o.attr.desigColumn ? o.attr.desigColumn : o.attr.name;
                    var field = o.name;
                    var keys = returnListKeys(o);
                    var search = '';
                 _.forEach(  keys, function (name, i) {
                        if (i < keys.length - 1) {
                            search += row[name] + '@';
                        } else {
                            search += row[name];
                        }
                    });
                    var result = _.find(data.loadedData[getComplexListIndex(o)], {VAL: search});
                    if (result == undefined) {
                        row[field] = "";
                    } else {
                        row[field] = result[fieldName];
                    }
                }
            });
        });

        self.postMessage(downloadCSV(dt));

答案 2 :(得分:6)

详细

  • Xcode 9.2,Swift 4
  • Xcode 10.2(10E125),Swift 5

解决方案

import Foundation

extension String { var toLocale: Locale { return Locale(identifier: self) } }

extension NumberFormatter {
    convenience init(numberStyle: NumberFormatter.Style, groupingSeparator: String?, decimalSeparator: String?) {
        self.init()
        set(numberStyle: numberStyle, groupingSeparator: groupingSeparator, decimalSeparator: decimalSeparator)
    }

    convenience init(numberStyle: NumberFormatter.Style, locale: Locale) {
        self.init()
        set(numberStyle: numberStyle, locale: locale)
    }

    func set(numberStyle: NumberFormatter.Style, groupingSeparator: String?, decimalSeparator: String?) {
        self.locale = nil
        self.numberStyle = numberStyle
        self.groupingSeparator = groupingSeparator
        self.decimalSeparator = decimalSeparator
    }

    func set(numberStyle: NumberFormatter.Style, locale: Locale?) {
        self.numberStyle = numberStyle
        self.locale = locale
    }
}

extension Numeric {
    func format(formatter: NumberFormatter) -> String? {
        if let num = self as? NSNumber { return formatter.string(from: num) }
        return nil
    }
}

用法

let formatter = NumberFormatter(numberStyle: .decimal, locale: "fr_FR".toLocale)
print(value.format(formatter: formatter))

formatter.set(numberStyle: .decimal, groupingSeparator: " ", decimalSeparator: ".")
print(value.format(formatter: formatter))

完整样本

  

不要忘记在此处添加解决方案代码

func test<T: Numeric>(value: T) {
    print("=========================================================")
    print("\(T.self), value = \(value)")

    let formatter = NumberFormatter(numberStyle: .decimal, locale: "fr_FR".toLocale)
    print(value.format(formatter: formatter) ?? "nil")
    formatter.set(numberStyle: .currency, locale: "de_DE".toLocale)
    print(value.format(formatter: formatter)  ?? "nil")
    formatter.set(numberStyle: .decimal, groupingSeparator: " ", decimalSeparator: ".")
    print(value.format(formatter: formatter)  ?? "nil")
}

func print(title: String, value: String?) {
    if let value = value { print("\(title) \(value)") }
}

test(value: Int(10000))
test(value: Double(10000.231))
test(value: Float(10000.231))

结果

=========================================================
Int, value = 10000
10 000
10.000,00 €
10 000
=========================================================
Double, value = 10000.231
10 000,231
10.000,23 €
10 000.231
=========================================================
Float, value = 10000.231
10 000,231
10.000,23 €
10 000.231

答案 3 :(得分:2)

对于前导零(Swift 5.2)

String(format: "%02d", intNumber) // 6 -> "06"
String(format: "%03d", intNumber) // 66 -> "066"
String(format: "%04d", intNumber) // 666 -> "0666"

来自:https://stackoverflow.com/a/25566860/1064316

答案 4 :(得分:1)

swift 4

extension Int {
    func formatnumber() -> String {
        let formater = NumberFormatter()
        formater.groupingSeparator = "."
        formater.numberStyle = .decimal
        return formater.string(from: NSNumber(value: self))!
    }
}

答案 5 :(得分:1)

实际上有一个更简单的解决方案(无需创建try/except实例),并且它考虑了用户的语言:

NumberFormatter

使用英语的值1000000的结果:

  

1,000,000

俄语:

  

1 000 000

p.s。在Android中与let result = String(format: "%ld %@", locale: Locale.current, viewCount, "views")

完全相同

答案 6 :(得分:0)

对于swift 4,我实现了一个扩展,我可以选择格式,如果没有选择则使用默认格式。

extension Int {
    func formatnumber(groupingSeparator: String?) -> String {
        let formater = NumberFormatter()
        formater.groupingSeparator = (groupingSeparator != nil) ? groupingSeparator! : ","
        formater.numberStyle = .decimal
        return formater.string(from: NSNumber(value: self))!
    }
}

答案 7 :(得分:-1)

我的脚本为例:

1)将扩展名添加到项目

extension String {

    public func subString(startIndex: String.Index, endIndex: String.Index) -> String {
        return String(self[startIndex...endIndex])
    }

    public func subString(_ from: Int, _ to: Int) -> String {
          let startIndex = self.index(self.startIndex, offsetBy: from)
          let endIndex = self.index(self.startIndex, offsetBy: to)
        return String(self[startIndex...endIndex])
    }
}

2)创建文件 Utilites.swift 并添加我的方法

public func  priceNumFormat(_ number: String)->String{

    var formattedNumber = number
    var print = number
    var prefix = ""

    if number.range(of:"-") != nil {
        let index = number.index(of:"-")
        formattedNumber.remove(at: index ?? formattedNumber.endIndex)
        prefix = "-"
    }


    if formattedNumber.range(of:".") != nil {
        let index = formattedNumber.index(of:".")
        formattedNumber =  formattedNumber.subString(startIndex: formattedNumber.startIndex, endIndex: index ?? formattedNumber.endIndex)
        formattedNumber.remove(at: index ?? formattedNumber.endIndex)
    }

    if formattedNumber.count == 8 //10 000 000
    {
       let num0 = formattedNumber.subString(0, 1)
       let num1 = formattedNumber.subString(2, 4)
       let num2 = formattedNumber.subString(5, 7)
       print =  "\(num0) \(num1) \(num2)"
    }

    if formattedNumber.count == 7 //1 000 000
    {
        let num0 = formattedNumber.subString(0, 0)
        let num1 = formattedNumber.subString(1, 3)
        let num2 = formattedNumber.subString(4, 6)
        print =  "\(num0) \(num1) \(num2)"
    }

    if formattedNumber.count == 6 //100 000
    {
        let num0 = formattedNumber.subString(0, 2)
        let num1 = formattedNumber.subString(3, 5)
        print =  "\(num0) \(num1)"
    }

    if formattedNumber.count == 5 //10 000
    {
        let num0 = formattedNumber.subString(0, 1)
        let num1 = formattedNumber.subString(2, 4)
        print =  "\(num0) \(num1)"
    }

    if formattedNumber.count == 4 //1 000
    {
        let num0 = formattedNumber.subString(0, 0)
        let num1 = formattedNumber.subString(1, 3)
        print =  "\(num0) \(num1)"
    }

    if formattedNumber.count == 3 //100
    {
        print =  formattedNumber
    }

    if prefix.count > 0
    {
        print = "- \(print)"
    }

    return print;
}

3)在您的UIController中添加代码

 let utils = Utilites()
            private func test(){
                var price =  self.utils.priceNumFormat("-12345678.000")
                print("\(price)") //-12 345 678
                price =  self.utils.priceNumFormat("-1234567.000")
                print("\(price)") //-1 234 567
                price =  self.utils.priceNumFormat("-123456.000")
                print("\(price)") //-123 456
                price =  self.utils.priceNumFormat("-12345.000")
                print("\(price)") //-12 345
                price =  self.utils.priceNumFormat("-1234.000")
                print("\(price)") //-1 234
                price =  self.utils.priceNumFormat("-123.000")
                print("\(price)") //-123

            }