简体   繁体   中英

Basic iOS Decimal Trim

I have float value 1.96, then I want to display 1.9 as string, if I use String(format: "%.1f") the result is 2.0, also I try to use NumberFormatter as extension

    let formatter = NumberFormatter()
    formatter.numberStyle = .decimal
    formatter.maximumFractionDigits = 1
    formatter.minimumFractionDigits = 1

    return formatter.string(for:  self)!

But still the result 2.0

is there any best way to achieved 1.96 to 1.9?

Old trick:

var yourResult = Double(floor(10*yourDecimalDigit)/10)

// yourResult = 1.9

Convert to string like this

var string = String(yourResult)

You can use general extension of Double to truncate the double value.

Swift 4.0

extension Double {
    func truncate(places : Int)-> Double {
        return Double(floor(pow(10.0, Double(places)) * self)/pow(10.0, Double(places)))
    }
}

Use it like this below

let trimedValue = 1.96.truncate(places: 1) // 1.9

Maybe there's methods can help you but I like to do it by myself

extension :

extension CGFloat{

    var onlyOneDigits : String {
        var str = "\(self)"
        let count = str.count 
        if self >= 1000 && self < 10000{
            str.removeLast(count - 6)
            return str
        }else if self >= 100{
            str.removeLast(count - 5)
            return str
        }else if self >= 10{
            str.removeLast(count - 4)
            return str
        }else{
            str.removeLast(count - 3)
            return str
        }
    }
}

Use it :

        let myFloat : CGFloat = 1212.1212
        let myStr : String = myFloat.onlyOneDigits
        print(myStr) // 1212.1

        let anotherFloat : CGFloat = 1.96
        let anotherStr : String = anotherFloat.onlyOneDigits
        print(anotherStr) // 1.9

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM