How to properly format currency on ios

后端 未结 7 1109
梦谈多话
梦谈多话 2020-12-01 09:19

I\'m looking for a way to format a string into currency without using the TextField hack.

For example, i\'d like to have the number \"521242\" converted into \"5,212

7条回答
  •  眼角桃花
    2020-12-01 09:42

    For Swift tested code (ref from AAV's code)

    func textField(textField: UITextField, shouldChangeCharactersInRange range: NSRange, replacementString string: String) -> Bool{
    
        let strMain : NSString = string
    
        let arrTemp : NSArray = (textField.text?.componentsSeparatedByCharactersInSet(NSCharacterSet.decimalDigitCharacterSet().invertedSet))!
        let str: NSString = arrTemp.componentsJoinedByString("")
    
        //NSInteger centAmount = cleanCentString.integerValue;
        var centAmount : NSInteger = str.integerValue
    
        if (string.length > 0)
        {
            // Digit added
            centAmount = centAmount * 10 + strMain.integerValue;
        }
        else {
            // Digit deleted
            centAmount = centAmount / 10;
        }
    
        let amount = (Double(centAmount) / 100.0)
    
        let currencyFormatter = NSNumberFormatter()
        currencyFormatter.numberStyle = .CurrencyStyle
        currencyFormatter.currencyCode = "USD"
        currencyFormatter.negativeFormat = "-¤#,##0.00"
        let convertedPrice = currencyFormatter.stringFromNumber(amount)
    
        print(convertedPrice)
    
        txtAmount.text = convertedPrice! //set text to your textfiled
        return false //return false for exact out put
    }
    

    note : if you want to remove the default currency symbol from input you can use currencySymbol to blank as below

    currencyFormatter.currencyCode = nil
    currencyFormatter.currencySymbol = ""
    

    Happy coding!

提交回复
热议问题