简体   繁体   English

不同区域 Swift 中的字符串到双精度转换 nil

[英]String to Double conversion nil in different region Swift

There is a text field有一个文本字段

@IBOutlet weak var txt: UITextField!

When I tried to convert the value of txt into Double its worked fine in US region.当我尝试将 txt 的值转换为 Double 时,它在美国地区运行良好。

For example例如

let magicNumber = Double(txt.text ?? "0.0")

If I type 12 UITextField then 12 assigned on magicNumber如果我输入 12 UITextField 然后在 magicNumber 上分配 12

Then I changed the region to Germany.然后我将地区更改为德国。

在此处输入图像描述

let magicNumber = Double(txt.text ?? "0.0")

If I type 12,8 UITextField then the magicNumber is nil.如果我输入 12,8 UITextField,那么 magicNumber 为 nil。

I need a correct double value like: 12.8我需要一个正确的双精度值,例如:12.8

How could I achieve this?我怎么能做到这一点? Please suggest to me the correct way.请向我建议正确的方法。

Careful handling of localized numeric strings小心处理本地化的数字字符串

let inputString = "12,8" 
let formatter = NumberFormatter()
formatter.locale = Locale.current // Locale(identifier: "de")
let number = formatter.number(from: inputString) 
print(number) // 12.8

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM