2015-08-07 39 views
35

Boooaaaaar !!! Spero che tutti possano aiutarmi? Come posso arrotondare il risultato a 2 cifre decimali e mostrarlo sull'etichetta del risultato? Ho trovato alcune affermazioni, ma sono nuovo di Swift ed è davvero difficile per me ricostruire gli esempi per il mio progetto.Formato valore float con 2 posizioni decimali

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 
    } 

} 

risposta

77

È possibile utilizzare standard di string formatting specifiers per arrotondare ad un numero arbitrario di cifre decimali. In particolare %.nf dove n è il numero di cifre decimali richiesti:

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

Supponendo che si desidera visualizzare il numero su ciascuna delle l* etichette:

@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) 
} 
+0

vedo tutti i questions.thanks earilier. ma non so dove metterlo nel mio codice ... – Andreas

+0

Avere una giocata mi aiuta sempre a capire le cose, avendo detto che ho aggiornato la risposta. –

+0

// Sarà più utile, specificando il punto decimale desiderato. let decimalPoint = 2 let floatAmount = 1.10001 let amountValue = String (formato: "% 0. * f", decimalPoint, floatAmount) –

Problemi correlati