Swift - How to remove a decimal from a float if the decimal is equal to 0?
Swift 3/4:
var distanceFloat1: Float = 5.0var distanceFloat2: Float = 5.540var distanceFloat3: Float = 5.03extension Float { var clean: String { return self.truncatingRemainder(dividingBy: 1) == 0 ? String(format: "%.0f", self) : String(self) }}print("Value \(distanceFloat1.clean)") // 5print("Value \(distanceFloat2.clean)") // 5.54print("Value \(distanceFloat3.clean)") // 5.03
Swift 2 (Original answer)
let distanceFloat: Float = (currentUser.distance! as NSString).floatValuedistanceLabel.text = String(format: distanceFloat == floor(distanceFloat) ? “%.0f" : "%.1f", distanceFloat) + "Km"
Or as an extension:
extension Float { var clean: String { return self % 1 == 0 ? String(format: "%.0f", self) : String(self) }}
Use NSNumberFormatter:
let formatter = NumberFormatter()formatter.minimumFractionDigits = 0formatter.maximumFractionDigits = 2// Avoid not getting a zero on numbers lower than 1// Eg: .5, .67, etc...formatter.numberStyle = .decimallet nums = [3.0, 5.1, 7.21, 9.311, 600.0, 0.5677, 0.6988]for num in nums { print(formatter.string(from: num as NSNumber) ?? "n/a")}
Returns:
3
5.1
7.21
9.31
600
0.57
0.7
extension
is the powerful way to do it.
Extension:
Code for Swift 2 (not Swift 3 or newer):
extension Float { var cleanValue: String { return self % 1 == 0 ? String(format: "%.0f", self) : String(self) }}
Usage:
var sampleValue: Float = 3.234print(sampleValue.cleanValue)
3.234
sampleValue = 3.0print(sampleValue.cleanValue)
3
sampleValue = 3print(sampleValue.cleanValue)
3
Sample Playground file is here.