Curnelious Curnelious - 6 months ago 13
Swift Question

A very strange String casting error

I am creating array of views with this labels :

0.1, 0.2 , 0.3, 0.4 ...... 20


so:

var time = 0.1
for k in 0..<200
{
//........
item.text = String(time) //*** here is the problem

time+=0.1


When it gets to 6 I get this on the label:

5.5 , 5.6 , 5.7 , 5.8 , 5.9, 5.99999,6.099999,6.199999


back to normal on
10.1 10.2 ,etc


Whats so special about 6 ?? :)

Answer

You can try to cast with a finite number of decimals, declare your time as a float and add it a float too:

var time = 0.1f
...

item.text = String(format:"%.1f", time)
time += 0.1f