Caio Luis Gomes Caio Luis Gomes - 4 months ago 14
iOS Question

Showing Doubles in Labels with AND without the decimal-point

(I apologize for any english mistakes, it's not my 1st language)

I need to solve this problem in order to continue to develop my app.

Here, I got a screenshot. (I know, it's ugly, I'm setting the constraints.)

The problem is: even when the number is a integer, it still shows as a rational. (ex.: 4 appears as 4.0, 16 as 16.0)

What I want is:


  • When the number in the textfield is integer, I want it to appear without the decimal-point. ( 4 appear as 4, 16 appear as 16)

  • When the number in the textfield is rational, I want it to appear with the decimal-point that belong to it. (4.2 appears as 4.2, 2.5 as 2.5)



What I don't want to happen:


  • Round any number. This will ruin the math. As I said, 4.22 needs to be 4.22 . But 4.0 needs to be only 4 .



I'll be very grateful for any help, thank you.

Answer

Do you want something like this?

let numberA: Float = 1.234
let numberB: Float = 7.000

func getStringFromNumber(number: Float) -> String {
    if number - Float(Int(number)) == 0 {
        return String("\(Int(number))")
    } else {
        return String("\(number)")
    }
}

print(getStringFromNumber(numberA)) // console output: 1.234
print(getStringFromNumber(numberB)) // console output: 7
Comments