Format float value with 2 decimal places

SwiftXcode6

Swift Problem Overview


How can I round the result to 2 decimal places and show it on the result label? I found some statements, but I´m new to Swift and it is actually difficult for me to rebuild the samples for my project.

import UIKit

class ViewController: UIViewController {
    
    @IBOutlet var txt: UITextField!
    
    @IBOutlet var l5: UILabel!
    @IBOutlet var l10: UILabel!
    @IBOutlet var l15: UILabel!
    @IBOutlet var l20: UILabel!
    @IBOutlet var l25: UILabel!
    @IBOutlet var l30: UILabel!
    @IBOutlet var l35: UILabel!
    @IBOutlet var l40: UILabel!
    
    @IBAction func Berechnen(sender: AnyObject) {
        
        var Zahl = (txt.text as NSString).floatValue
        
        l5.text  = "\((Zahl / 95) * (100))"
        l10.text = "\((Zahl / 90) * (100))"
        l15.text = "\((Zahl / 85) * (100))"
        l20.text = "\((Zahl / 80) * (100))"
        l25.text = "\((Zahl / 75) * (100))"
        l30.text = "\((Zahl / 70) * (100))"
        l35.text = "\((Zahl / 65) * (100))"
        l40.text = "\((Zahl / 60) * (100))"
    }
    
    func textFieldShouldReturn(textField: UITextField) -> Bool {
        self.view.endEditing(true)
        return false
    }

}

Swift Solutions


Solution 1 - Swift

You can use standard string formatting specifiers to round to an arbitrary number of decimal places. Specifically %.nf where n is the number of decimal places you require:

let twoDecimalPlaces = String(format: "%.2f", 10.426123)

Assuming you want to display the number on each of the l* labels:

@IBAction func Berechnen(sender: AnyObject) {

    var Zahl = (txt.text as NSString).floatValue

    l5.text  = String(format: "%.2f", (Zahl / 95) * 100)
    l10.text = String(format: "%.2f", (Zahl / 90) * 100)
    l15.text = String(format: "%.2f", (Zahl / 85) * 100)
    l20.text = String(format: "%.2f", (Zahl / 80) * 100)
    l25.text = String(format: "%.2f", (Zahl / 75) * 100)
    l30.text = String(format: "%.2f", (Zahl / 70) * 100)
    l35.text = String(format: "%.2f", (Zahl / 65) * 100)
    l40.text = String(format: "%.2f", (Zahl / 60) * 100)
}

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionAndreasView Question on Stackoverflow
Solution 1 - SwiftSteve WilfordView Answer on Stackoverflow