-2

I am doing some programming inside a TableView which is getting some Json data and one of the elements coming back is of type Float and I am having trouble using the text property on a float this is my code

    var latitudes = [Float]()
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
    let cell = tableView.dequeueReusableCell(withIdentifier: "mycelia", for: indexPath) 
      // This gives error can't convert type String to Float
    cell.MyLabel.text = latitudes[indexPath.row]


    return cell
}

I am new to Swift and have tried other methods such as what is explained here Convert String to float in Apple's Swift but can not get it to work

Community
  • 1
  • 1
Rome Torres
  • 1,061
  • 2
  • 13
  • 27
  • 2
    Actually you have it backwards. What you need to do here is convert a Float to a String. – matt Nov 15 '16 at 21:23

2 Answers2

1

Just pass it into a String initializer:

cell.MyLabel.text = String(latitudes[indexPath.row])
Alexander
  • 59,041
  • 12
  • 98
  • 151
1

If you want to support a whatever Locale the device may be using, you should use NumberFormatter. This is important because some locales use a . for a decimal point, whereas others (e.g. Germany) use ,.

So, you might define a number formatter property:

let formatter: NumberFormatter = {
    let _formatter = NumberFormatter()
    _formatter.maximumFractionDigits = 6  // use however many decimal places you want
    _formatter.minimumFractionDigits = 6
    return _formatter
}()

Then you can do:

cell.MyLabel.text = formatter.string(from: NSNumber(value: latitudes[indexPath.row]))

This way, when considering a latitude like 42.67, a US user will see a string of 42.670000 but the German user will see the appropriate 42,670000 string.

Rob
  • 415,655
  • 72
  • 787
  • 1,044