gpt4 book ai didi

ios - 为什么我的字符串格式化程序使参数 0.00 而不是它的实际值

转载 作者:行者123 更新时间:2023-12-01 21:42:45 25 4
gpt4 key购买 nike

我希望这是一个小修复,但我有一个文本字段,它是用户输入的数字。它的导出称为 billTextField。我需要将其更改为浮点数/ double 数而不是字符串,但我希望它不会超过小数点后两位。我调试了,当我去的时候

Double(billTextField.text ?? "") ?? 1

它打印正确的值,但是当我尝试使用字符串格式化程序时
Double(String(format: "%.2f", billTextField.text ?? "")) ?? 2

即使我的文本字段显示 125.50 或任何其他数字,该值也会变为 0.00。我认为它一定是导致这种情况的字符串格式化程序,有什么想法吗?

最佳答案

这里的问题是 String(format:)您需要提供第二个参数为 Double , 就是这样:

let doubleValue = Double(billTextField.text!) ?? 0 // You can force unwrap strings since it never returns nil credits @Leo
let roundedDoubleValue = Double(String(format: "%.2f", doubleValue)) ?? 2

或使用 round像这样在 Double 上:
let roundedDoubleValue = Double(round(100*doubleValue)/100) // number of zeros for number of places

关于ios - 为什么我的字符串格式化程序使参数 0.00 而不是它的实际值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62441651/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com