Swiftui Textfield四舍五入输入问题
我有一个textfield圆形问题。如果我输入1到1.49的任何地方都很好。如果我输入1.5或向上(至1.999),则该字段最多可达2个。如何将其保留为我的输入。如果我输入1.73,我希望它保留1.73,而不是2。这是代码:
VStack {
let lineOneProxy = Binding<String>(
get: { if self.lineOne == 0 {
return ""
} else {
return String(format: "%.0f", Double(self.lineOne)) }
},
set: { if let value = NumberFormatter().number(from: $0) {
self.lineOne = value.doubleValue }
}
)
TextField("ENTER", text: lineOneProxy.max(5))
}
这是我设置NumberFormatter的方式:
extension NumberFormatter {
convenience init(numberStyle: Style, locale: Locale = .current) {
self.init()
self.locale = locale
self.numberStyle = numberStyle
}
}
I'm having a textfield rounding issue. If I input anywhere from 1 to 1.49 all is good. If I input 1.5 or up (to 1.999) the field rounds up to 2. How do I keep this as what I input. If I input 1.73 I want it to remain 1.73, not 2. Here's the code:
VStack {
let lineOneProxy = Binding<String>(
get: { if self.lineOne == 0 {
return ""
} else {
return String(format: "%.0f", Double(self.lineOne)) }
},
set: { if let value = NumberFormatter().number(from: $0) {
self.lineOne = value.doubleValue }
}
)
TextField("ENTER", text: lineOneProxy.max(5))
}
This is how I have NumberFormatter set up:
extension NumberFormatter {
convenience init(numberStyle: Style, locale: Locale = .current) {
self.init()
self.locale = locale
self.numberStyle = numberStyle
}
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
因为那是您告诉它要做的。在此行中:
指定
%。0F
表示以NO(0)分数数字为单位的一半汇总。给定一个双
value = 1234.12345
,编辑:
您问为什么要获得值。答案很明显,如果您不想要这种行为,请不要使用``%.0f''格式化。您需要2个分数数字,使用您创建的格式化器并将其编辑为:
使用以下方式:
Because that is what you told it to do. In this line:
specifying
%.0f
means to round up at half with no(0) fractional digits.Given a double
value = 1234.12345
,Edit:
You asked why you were getting the value that you were. The answer is obvious, if you don't want the behavior,do not use the `%.0f" formatter. You never said what outcome you specifically wanted, but I am guessing 2 fractional digits from the way you worded some things. If you want 2 fractional digits, use the formatter you created and edit it to this:
Use it like: