首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >将UITextField格式化为价格(XXX,XXX.XX)

将UITextField格式化为价格(XXX,XXX.XX)
EN

Stack Overflow用户
提问于 2011-09-09 04:56:11
回答 2查看 1.9K关注 0票数 4

我一直在绞尽脑汁寻找解决方案。

我只是想要一个UITextField来正确地格式化一个输入的数字作为价格。这意味着只允许一个小数点,小数点后两个数字(如果他们是输入的)和一个',‘来分隔大数字(例如150,000)。

这就是价格正确格式化的方式,那么为什么正确的价格这么难呢?

我最接近的解决方案是this code。然而,它的问题是,在键入四位数字后,它将恢复为0??这已经接近解决方案了,我就是不明白为什么它会有这种奇怪的行为。

EN

回答 2

Stack Overflow用户

发布于 2011-09-09 05:32:01

你实际上不需要任何代码来做这件事。只需在nib文件中的文本字段上拖动一个数字格式化程序,并将其配置为使用"Currency“样式。

通过代码,这将是[myNumberFormatter setNumberStyle:NSNumberFormatterCurrencyStyle]

请注意,价格的格式因地区不同而有很大差异。例如,在德国,点用作千位分隔符,逗号用作小数点。使用样式而不是固定的格式可以为您处理这些差异。

票数 1
EN

Stack Overflow用户

发布于 2018-02-05 21:28:51

嗨,这是我的解决方案。

代码语言:javascript
运行
复制
import UIKit


extension Numeric {   // for Swift 3 use FloatingPoint or Int

    func currency(locale: String, symbol: Bool = true) -> String {
        let formatter = NumberFormatter()
        formatter.numberStyle = .currency
        formatter.locale = Locale(identifier: locale)
        if !symbol {
            formatter.currencySymbol = ""
        }
        let result = formatter.string(for: self) ?? ""

        return result
    }

}

ViewController代码

代码语言:javascript
运行
复制
var price: String!
var priceNumber: CGFloat!
@IBOutlet weak var priceInput: UITextField!

ViewDidLoad

代码语言:javascript
运行
复制
priceInput.addTarget(self, action: #selector(priceInputChanged), for: .editingChanged)
priceInput.tintColor = .clear

priceInput.delegate = self

UITextFieldDelegate in Your ViewController

代码语言:javascript
运行
复制
@objc func priceInputChanged(_ textField: UITextField){

    if localIdentifier != nil {
        priceInput.text = priceNumber.currency(locale: localIdentifier, symbol: false)
    }
}
func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool {

    if textField.tag == 3 {

        if string.isEmpty {
            if price.count > 0 {
                let last = price.removeLast()
                if last == "." {
                    if price.count > 0 {
                        price.removeLast()
                    }
                }
            }

        }else {
            price.append(string)
        }

        if let input = price {
            let n = NumberFormatter().number(from: input) ?? 0
            priceNumber = CGFloat(truncating: n)

            if localIdentifier != nil {
                priceInput.text = priceNumber.currency(locale: localIdentifier, symbol: false)
            }

        }

    }

    return true
}

就这样

票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/7354383

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档