Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Swift - How to remove a decimal from a float if the decimal is equal to 0?

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" 
like image 324
Kali Aney Avatar asked Jul 13 '15 18:07

Kali Aney


People also ask

Can float have no decimal?

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.

How do you omit a decimal?

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.

How do I restrict float to 2 decimal places?

We will use %. 2f to limit a given floating-point number to two decimal places.

How do you remove decimals from data labels?

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.


1 Answers

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)     } } 
like image 88
Frankie Avatar answered Sep 23 '22 05:09

Frankie