货币格式化swift 3

时间:2017-04-24 07:36:51

标签: ios swift swift3

我正在尝试使用其委托方法格式化货币标准格式的文本字段输入,但找到的解决方案并不符合要求。我也找到了一些解决方案,但我找不到预期的解决方案。

要求:

  

UITextField的输入:300000

     

获取: 30,0000

     

期望输出: 300,000

使用代码:

//MARK:- textfield delegate method
func textField(_ textField: UITextField, shouldChangeCharactersIn range:NSRange, replacementString string: String) -> Bool {

    guard let textFieldHasText = (textField.text), !textFieldHasText.isEmpty else {
        //early escape if nil
        return true
    }

    if textField == self.reqCourps || textField == self.presentInvest{
        let formatter = NumberFormatter()
        formatter.numberStyle = .decimal

        //remove any existing commas
        let textRemovedCommma = textFieldHasText.replacingOccurrences(of: ",", with: "")

        //update the textField with commas
        let formattedNum = formatter.string(from: NSNumber(value: Int(textRemovedCommma)!))

        textField.text = formattedNum
    }


    guard let text = textField.text else { return true }
    let newLength = text.characters.count + string.characters.count - range.length
    return newLength <= 12 // Bool

}

当我使用.currency方法时,它也会崩溃应用程序:

formatter.numberStyle = .currency

3 个答案:

答案 0 :(得分:0)

这是代码

func getNumberWithFormat(_ number : NSNumber, format : String) -> String {
     let numberFormatter = NumberFormatter()
     numberFormatter.locale = Locale.current
     numberFormatter.numberStyle = NumberFormatter.Style.decimal
     numberFormatter.usesGroupingSeparator = true

     numberFormatter.positiveFormat = format
     return numberFormatter.string(from: number)! 
}

您可以将此功能称为

let number : NSNumber = 300000 
print("Number is : ", getNumberWithFormat(number, format: "###,###"))

您的输出将是

Number is :  300,000

答案 1 :(得分:0)

我认为这是由于您的区域设置。在世界的某些地区,他们有这样的数字格式。我测试了你的代码并且它工作正常,所以我猜你的语言环境一定有问题。

如果您希望数字采用美国风格,只需明确设置区域设置:

// here pass your textfield value that you want to convert into doller.

 let price = NSDecimalNumber(string: self.textfield.text) as NSNumber
 let formatter = NumberFormatter()
 formatter.numberStyle = .currency
 formatter.locale = Locale(identifier: "en_US")
 formatter.string(from: price)
 print(formatter.string(from: price)!)

输出:

$8,965.00

答案 2 :(得分:0)

import UIKit

open class DecimalFormatter: NumberFormatter {

    public override init() {
        super.init()
        locale = Locale.current
        numberStyle = .decimal
        minimumFractionDigits = 2
        maximumFractionDigits = 2
    }

    required public init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }

    override open func getObjectValue(_ obj: AutoreleasingUnsafeMutablePointer<AnyObject?>?, for string: String, range rangep: UnsafeMutablePointer<NSRange>?) throws {
        guard obj != nil else { return  }
        let str = string.components(separatedBy: CharacterSet.decimalDigits.inverted).joined(separator: "")
        obj?.pointee = NSNumber(value: (Double(str) ?? 0.0)/Double(pow(10.0, Double(minimumFractionDigits))))
    }
}


let originString = NSNumber.init(value: 30000)
let result = DecimalFormatter().string(from: originString)
你会得到30,000.00 如果你想得到30,000,只需改变&#34; minimumFractionDigits&#34;到&#34; 0&#34;