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

发布于 2024-12-03 19:16:47 字数 380 浏览 1 评论 0原文

我一直在绞尽脑汁试图找到解决这个问题的办法。

我只是希望 UITextField 将输入的数字正确格式化为价格。这意味着只允许使用一个小数点、小数点后两位数字(如果输入的话)以及用于分隔大数字(例如 150,000)的“,”。

这就是价格的正确格式,那么为什么正确格式如此困难呢?

我最接近的解决方案是 此代码。然而,它的问题是,输入四位数字后,它会恢复为 0?这接近解决方案,我只是不明白为什么它会做出这种奇怪的行为。

I've been tearing my hair out trying to find a solution to this.

I simply want a UITextField to correctly format an inputted number as a price. That means only a single decimal point is allowed, two digits after the point (if they were typed in) and a ',' to separate large numbers (eg 150,000).

That is how a price is properly formatted, so why is it so difficult to get right?

The closest I've come to a solution is this code. The problem with it, however, is after typing in four digits it reverts to 0?? This is close to a solution, I just can't understand why it does this strange behavior.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

寄离 2024-12-10 19:16:47

实际上您不需要任何代码。只需将数字格式化程序拖到 nib 文件中的文本字段上,并将其配置为使用“货币”样式即可。

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

请注意,价格的格式因区域设置而异。例如,在德国,点用作千位分隔符,逗号用作小数点。使用样式而不是固定格式可以为您解决这些差异。

You actually don't need any code for this. Just drag a number formatter on your text field in the nib file and configure it to use the "Currency" style.

Via code this would be [myNumberFormatter setNumberStyle:NSNumberFormatterCurrencyStyle]

Beware that the format of prices is very different depending on the locale. In Germany for example, the dot is used as a thousands separator and the comma as the decimal point. Using a style instead of a fixed format takes care of those differences for you.

时光暖心i 2024-12-10 19:16:47

嗨这是我的解决方案。

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 代码

var price: String!
var priceNumber: CGFloat!
@IBOutlet weak var priceInput: UITextField!

ViewDidLoad

priceInput.addTarget(self, action: #selector(priceInputChanged), for: .editingChanged)
priceInput.tintColor = .clear

priceInput.delegate = self

ViewController 中的 UITextFieldDelegate

@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
}

就是这样

Hi Here is my solution.

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 Code

var price: String!
var priceNumber: CGFloat!
@IBOutlet weak var priceInput: UITextField!

ViewDidLoad

priceInput.addTarget(self, action: #selector(priceInputChanged), for: .editingChanged)
priceInput.tintColor = .clear

priceInput.delegate = self

UITextFieldDelegate in Your ViewController

@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
}

That's It

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文