Brewski
Brewski

Reputation: 684

Remove empty decimal values Swift 3

I'm building a calculator app and I'm trying to get the text.label to only display decimal values if they are not empty, for example; 5 + 5 = 10, at the moment it shows 10.0 because I am using floats. Do I create a function that I call every time before I print the result to the screen, that seems unnecessary to me?

Upvotes: 1

Views: 962

Answers (1)

Muhammad Usman Piracha
Muhammad Usman Piracha

Reputation: 199

Extension

Swift 3

extension Float {
   var cleanValue: String {
       return self.truncatingRemainder(dividingBy: 1) == 0 ? String(format: "%.0f", self) : String(self)
   }
}

Swift 2

extension Float {
    var cleanValue: String {
        return self % 1 == 0 ? String(format: "%.0f", self) : String(self)
    }
}

Usage

 var sampleValue: Float = 3.234
 print(sampleValue.cleanValue)
 //Output = 3.234
 sampleValue = 3
 print(sampleValue.cleanValue)
 //Output = 3

Upvotes: 1

Related Questions