逗号分隔的数字与 2 位小数 - swift [英] comma separated number with 2 digit fraction - swift

查看:25
本文介绍了逗号分隔的数字与 2 位小数 - swift的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个文本字段,它的输入是价格,所以我想得到两个这样的:1,111,999.99.我写信使之成为可能,但有两个问题.首先,在四位数字和 2 位小数位(如 1,234.00)之后,它重置为零.其次,我不能把分数放在里面(分数总是 .00)我如何制作一个接收 1,111,999.99 作为输入的文本字段?

I have a textfield that it's input is price, so I want to get both like this: 1,111,999.99. I wrote to make it possible but there are two problems. First, after four digits and 2 fraction digit (like 1,234.00) it resets to zero. Second, I can't put fraction in it (fraction is always .00) how can i make a textfield that receives 1,111,999.99 as input?

在我的自定义 UITextfield 中:

in my custom UITextfield:

private var numberFormatter: NumberFormatter {
    let formatter = NumberFormatter()
    formatter.maximumFractionDigits = 2
    formatter.minimumFractionDigits = 0
    formatter.numberStyle = .decimal
    formatter.decimalSeparator = "."
    formatter.groupingSeparator = ","
    return formatter
}

var commaValue: String {
    return numberFormatter.string(from: value)!
}

var value: NSNumber {
    let number = numberFormatter.number(from: self.text ?? "0")
    return number!
}

在我的 textfieldDidChange 方法中:

and in my textfieldDidChange method:

@IBAction func textfieldEditingChanged(_ sender: Any) {
    let textfield = sender as! UITextField
    textfield.text = textfield.commaValue
}

推荐答案

暂时这样解决:

var formattedNumber: String {
    guard self.text != "" else {return ""}
    var fraction = ""
    var digit = ""

    let fractionExists = self.text!.contains(".")

    let num = self.text?.replacingOccurrences(of: ",", with: "")
    let sections = num!.characters.split(separator: ".")
    if sections.first != nil
    {
        let str = String(sections.first!)
        let double = Double(str)
        guard double != nil else {return self.text ?? ""}
        digit = numberFormatter.string(from: NSNumber(value: double ?? 0))!
    }
    if sections.count > 1
    {
        fraction = String(sections[1])
        if fraction.characters.count > 2
        {
            fraction = String(fraction.prefix(2))
        }
        return "\(digit).\(fraction)"
    }
    if fractionExists
    {
        return "\(digit)."
    }
    return digit
}

.

@IBAction func textfieldEditingChanged(_ sender: Any) {
    let textfield = sender as! UITextField
    textfield.text = textfield.formattedNumber
}

这篇关于逗号分隔的数字与 2 位小数 - swift的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆