1

I know this might be a simple question but I didn't find an answer for Swift: How can I display a Float variable in a label. I get the error: "Float is not convertible to String".

I don't want to convert the float into string because I want to calculate with it...

maidi
  • 3,219
  • 6
  • 27
  • 55

3 Answers3

7

We can do it in several ways.

Method 1:

lable.text = "\(float)"

Method 2:

lable.text = NSString(format: "%.2f", f)

Method 3:

let numberFormatter = NSNumberFormatter() numberFormatter.numberStyle = .DecimalStyle lable.text = numberFormatter.stringFromNumber(f)

Method 4:

Starting from Xcode 6.3, we can use float.description to get string value

lable.text = float.description

Karthi
  • 575
  • 5
  • 17
1
label.text = "\(floatvariable)"
derdida
  • 14,784
  • 16
  • 90
  • 139
0

Alternatively, you can use NSNumberFormatter if you want more control over the number formatting:

let nf = NSNumberFormatter()
nf.numberStyle = NSNumberFormatterStyle.DecimalStyle
nf.maximumFractionDigits = 2
label.text = nf.stringFromNumber(floatvariable)
Romain
  • 3,718
  • 3
  • 32
  • 48