I'm displaying a distance with one decimal, and I would like to remove this decimal in case it is equal to 0 (ex: 1200.0Km), how could I do that in swift? I'm displaying this number like this:
let distanceFloat: Float = (currentUser.distance! as NSString).floatValue distanceLabel.text = String(format: "%.1f", distanceFloat) + "Km"
If doing math with floats, you need to add a decimal point, otherwise it will be treated as an int. See the Floating point constants page for details. The float data type has only 6-7 decimal digits of precision. That means the total number of digits, not the number to the right of the decimal point.
Step 1: Write down the decimal divided by 1. Step 2: Multiply both top and bottom by 10 for every number after the decimal point. (For example, if there are two numbers after the decimal point, then use 100, if there are three then use 1000, etc.) Step 3: Simplify (or reduce) the Rational number.
We will use %. 2f to limit a given floating-point number to two decimal places.
Right click on one of the decimal value on the graph and go to format y/x axis and under number tab you have an option to make the decimal places to 0.
Swift 3/4:
var distanceFloat1: Float = 5.0 var distanceFloat2: Float = 5.540 var distanceFloat3: Float = 5.03 extension Float { var clean: String { return self.truncatingRemainder(dividingBy: 1) == 0 ? String(format: "%.0f", self) : String(self) } } print("Value \(distanceFloat1.clean)") // 5 print("Value \(distanceFloat2.clean)") // 5.54 print("Value \(distanceFloat3.clean)") // 5.03
Swift 2 (Original answer)
let distanceFloat: Float = (currentUser.distance! as NSString).floatValue distanceLabel.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) } }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With