格式化带有 2 个小数位的浮点值 [英] Format float value with 2 decimal places

查看:30
本文介绍了格式化带有 2 个小数位的浮点值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何将结果四舍五入到小数点后两位并显示在结果标签上?我找到了一些陈述,但我是 Swift 的新手,实际上我很难为我的项目重建示例.

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
    }

}

推荐答案

您可以使用标准的 字符串格式说明符 以四舍五入到任意数量的小数位.特别是 %.nf,其中 n 是您需要的小数位数:

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)

假设您想在每个 l* 标签上显示数字:

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)
}

这篇关于格式化带有 2 个小数位的浮点值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆