[英]Only show my float number to a certain decimal place - Swift
basically I want to remove the decimal places for my step calories burnt calculation. 基本上,我想删除卡路里消耗小数位。 I know I need to add something to
self.total2.text = ("\\(String(bmi)) kcal")
but just need a quick bit of advice on achieving this. 我知道我需要在
self.total2.text = ("\\(String(bmi)) kcal")
添加一些内容,但是只需要一些关于实现这一点的快速建议。
@IBAction func calc2(_ sender: Any) {
if self.value111.text! != "" && self.value222.text! != "" {
let textfieldInt = Float(value111.text!)
let textfield2Int = Float(value222.text!)
var bmi:Float = (((textfieldInt! * 2.204623) * 0.5) / 1500) * textfield2Int!
self.total2.text = ("\(String(bmi)) kcal")
let banner = StatusBarNotificationBanner(title: "Calculation Done! Submit to save. ✅", style: .warning)
banner.show(queuePosition: .front)
}
}
@IBAction func submit2(_ sender: Any) {
let dict = (["kcal": self.total.text!, "date": self.getDate()])
ref?.child("user").child(Auth.auth().currentUser!.uid).child("measurements").child("calculations").child("kcal").child("\(getDate())").setValue(dict)
total.text = ""
let banner = NotificationBanner(title: "Success, Step Calories Burnt has been saved today ⚖️", style: .success)
banner.show(queuePosition: .front)
}
Have a look at the NumberFormatter
class, which lets you fine-tune the string representation of a numeric value, whether integer or floating-point. 看一下
NumberFormatter
类,它使您可以微调数值(整数或浮点数)的字符串表示形式。 Set up the NumberFormatter
to produce the output in the format you want, then call string(from:)
to create a string from your number. 设置
NumberFormatter
以所需的格式生成输出,然后调用string(from:)
从您的数字创建字符串。
Use a NumberFormatter
(have a look here ) 使用
NumberFormatter
( 在这里查看 )
let bmi:Float = (((textfieldInt! * 2.204623) * 0.5) / 1500) * textfield2Int!
let formatter = NumberFormatter()
//Set the min and max number of digits to your liking, make them equal if you want an exact number of digits
formatter.minimumFractionDigits = 1
formatter.maximumFractionDigits = 3
self.total2.text = formatter.string(from: NSNumber(value: bmi)) + " kcal"
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.