0

Im a total newbie to Swift and pretty poor in English. However, I'm trying to build a priceless we use in our company.

I want the user to type in some figures, and let them know the price. It contains a lot of variables but i think everyone is configured the same.

Lets say i want the user to type in an amount in at UiTextField, and a label shall display 1000 / amount with two decimals.

My code at this point is this;

import UIKit
import Foundation

class ViewController: UIViewController {
    @IBOutlet weak var svar: UILabel!
    @IBOutlet weak var inpu2: UITextField!

    override func viewDidLoad() {
        super.viewDidLoad()
         svar.text = ""
    }

    @IBAction func input(_ sender: Any) {
        if let treStørrelse = Float(inpu2.text!) {
            svar.text = "\(1000 / treStørrelse)"
        }
    }
}

My output at this point is shown as xx.xxxxxxxxxx I want it to be shown xx.xx

I also need to use the answer in further calculation.

Yannick Loriot
  • 7,107
  • 2
  • 33
  • 56

1 Answers1

1

In your case the easiest and more safe way is to use the NumberFormatter object:

lazy var numberFormatter: NumberFormatter = {
  let nf = NumberFormatter()
  nf.minimumFractionDigits = 2
  nf.maximumFractionDigits = 2

  return nf
}()

@IBAction func input(_ sender: Any) {
    if let text = inpu2.text, let treStørrelse = Float(text) {
        svar.text = numberFormatter.string(for: 1000 / treStørrelse)
    }
}

Here the expected output will be rounded to the second decimal, and it'll always display 2 decimals. For instance:

  • 4 is interpolated as 4.00
  • 4.6 is interpolated as 4.60
  • 4.4374 is interpolated as 4.44
  • 4.4324 is interpolated as 4.43
Yannick Loriot
  • 7,107
  • 2
  • 33
  • 56
  • 1
    Presenting numbers to users should be *always* done using `NumberFormatter`. Interpolation is not properly localized. Good enough for data encoding or for console logs but not for presentation to users. – Sulthan Jan 20 '19 at 14:33
  • @Sulthan you've right, I forgot this option. Thank you for the reminder! – Yannick Loriot Jan 20 '19 at 14:36
  • Sadly, all the duplicates show interpolation as the highest voted answer while `NumberFormatter` should be the first option almost always. – Sulthan Jan 20 '19 at 14:40
  • I've updated my answer to use the `NumberFormatter` instead of the string interpolation in order to provide a "good" solution – Yannick Loriot Jan 20 '19 at 14:51
  • 1
    You can use `numberFormatter.string(for: 1000 / treStørrelse)`. (I would also check that `treStørrelse` is not zero though) – Sulthan Jan 20 '19 at 14:52