user3851362
user3851362

Reputation: 11

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?

Upvotes: 0

Views: 87

Answers (3)

mazen
mazen

Reputation: 448

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

Upvotes: 0

Jaydeep Vora
Jaydeep Vora

Reputation: 6213

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

Upvotes: 1

Akshansh Thakur
Akshansh Thakur

Reputation: 5341

Old trick:

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

// yourResult = 1.9

Convert to string like this

var string = String(yourResult)

Upvotes: 1

Related Questions