尝试在 Swift 中组合数字和变量

发布于 2025-01-15 13:42:54 字数 377 浏览 4 评论 0原文

我是一个新手,试图通过将数字和变量组合在一起来创建 0.2。但我想我已经把一切都倒退了。有人可以帮忙吗?

//将字符串“20%”转换为“2”。

let tipPercent = tip.prefix(1)

//将字符串转换为 Int '2'

let tipPercent1: Int = Int(tipPercent) ?? 0 

//所以现在我想将 0. 与变量tipPercent1结合起来。这将创建“0.2”

let twentyTipamount = (billamount * 0.tipPercent1) + billamount

I am a newbie trying hard to create 0.2 from combining a a number and a variable together. But I think I have it all backwards somehow. can anyone help?

//turns a string of '20%' into '2'.

let tipPercent = tip.prefix(1)

//turns the string into a Int of '2'

let tipPercent1: Int = Int(tipPercent) ?? 0 

//So now I want to combine the 0. with the variable tipPercent1. this will create '0.2'

let twentyTipamount = (billamount * 0.tipPercent1) + billamount

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

美羊羊 2025-01-22 13:42:54

看起来您只想将百分比字符串解析为数字。您应该使用NumberFormatter

let numberFormatter = NumberFormatter()
numberFormatter.locale = Locale(identifier: "en-US_POSIX")
// or whatever other locale that your tip is written in

numberFormatter.numberStyle = .percent
// if the tip cannot be parsed, use 0 as the default
let tipRate = numberFormatter.number(from: tip)?.doubleValue ?? 0
// or you can do something else:
// guard let tipRate = numberFormatter.number(from: tip)?.doubleValue else { ... }

// calculate the amount after tips
let totalAmount = billamount * (1 + tipRate)

It seems like you just want to parse a percent string into a number. You should use a NumberFormatter.

let numberFormatter = NumberFormatter()
numberFormatter.locale = Locale(identifier: "en-US_POSIX")
// or whatever other locale that your tip is written in

numberFormatter.numberStyle = .percent
// if the tip cannot be parsed, use 0 as the default
let tipRate = numberFormatter.number(from: tip)?.doubleValue ?? 0
// or you can do something else:
// guard let tipRate = numberFormatter.number(from: tip)?.doubleValue else { ... }

// calculate the amount after tips
let totalAmount = billamount * (1 + tipRate)
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文