Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
255 views
in Technique[技术] by (71.8m points)

ios - FloatValue with 2 decimals from textField

In my Core Data app I save 3 Floating point numbers from 3 UITexFields. To do that I had to convert them to Strings.

Now the problem is that the values are rounded to .0.

How do I do it?

nyTankning.liter = (textFieldLiter.text as NSString).floatValue
nyTankning.kronor = (textFieldKronor.text as NSString).floatValue
nyTankning.literpris = (textFieldLiterpris.text as NSString).floatValue 
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Your problem there is that you are trying to use a comma "," instead of a period "."

struct Number {
    static let formatter = NumberFormatter()
}
extension String {
    var converted: String? {
        return fractionDigits()
    }
    var doubleValue: Double? {
        return Number.formatter.number(from: self)?.doubleValue
    }
    var floatValue: Float? {
        return Number.formatter.number(from: self)?.floatValue
    }
    func fractionDigits(min: Int = 2, max: Int = 2) -> String? {
        Number.formatter.decimalSeparator = "."
        if let result = Number.formatter.number(from: self) {
            Number.formatter.minimumFractionDigits = min
            Number.formatter.maximumFractionDigits = max
            return Number.formatter.string(from: result)
        } else {
            Number.formatter.decimalSeparator = ","
            if let result = Number.formatter.number(from: self) {
                Number.formatter.minimumFractionDigits = min
                Number.formatter.maximumFractionDigits = max
                return Number.formatter.string(from: result)
            }
        }
        return nil
    }
}

"1,1222".converted              // "1.12"
"2".converted                   // "2.00"

"1,1222".converted?.doubleValue  // 1.12
"2".converted?.doubleValue       // 2.0

"1,1222".converted?.floatValue   // 1.12000000476837
"2".converted?.floatValue        // 2.0

"1.1222".converted              // "1.12"
"1.1222".converted?.doubleValue  // 1.12
"1.254".converted?.floatValue    // 1.25

"1.254".fractionDigits(min: 1, max: 2) // "1.25"
"1.2".fractionDigits(min: 1, max: 2)   // "1.2"

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...