Search code examples
iosswiftdoubletextfielddecimal-point

Showing Doubles in Labels with AND without the decimal-point


To check the best answer, scroll down to Paulw11's answer.

(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.


Solution

  • You can simply use the %g formatting option:

    deltaValueS.text = String(format:"∆ é %g",deltaValue)
    
    • For 4.0 this will give "∆ é 4"
    • For 4.123 this will give "∆ é 4.123"