简体   繁体   English

iOS SWIFT 4使用区域设置将字符串转换为十进制

[英]IOS SWIFT 4 convert String to Decimal with Locale

In IOS SWIFT 4, I am trying to create a Decimal out of a given String for Money calculations considering the Current Locale (Mainly considering Decimal Separator & GroupingSeparator) 在IOS SWIFT 4中,我尝试根据给定的String for Money计算创建一个小数 ,考虑到当前语言环境 (主要考虑小数分隔符和分组分隔符)

Just tried to use Decimal initialization with Locale, BUT as explains in this link if the string contains a non-numeric character, it just reads up to that character rather than providing nil . 只是尝试将Decimal初始化与Locale,BUT结合使用,如该链接中所述,如果字符串包含非数字字符,则它只会读取该字符,而不是提供nil So I wouldn't know if the string has successfully converted to Decimal or partially considered. 所以我不知道字符串是否已成功转换为Decimal或已部分考虑。 eg In following case if the number string (stringValue) has grouping separator it just reads until up to that character (which is comma). 例如,在以下情况下,如果数字字符串(stringValue)具有分组分隔符,它将一直读取直到该字符(逗号)为止。 So following code provides answer as 1. 所以下面的代码提供答案为1。

let stringValue: String = "1,200.00"
let decValue: Decimal = Decimal(string: stringValue, locale: Locale(identifier: "en_GB")) // ANSWER - 1

That's the problem with Decimal Initialisation. 这就是十进制初始化的问题。 I can resolve that grouping separator problem with NumberFormatter as follows but decimalValue property in converted NSNumber is providing wrong value. 我可以使用NumberFormatter解决以下分组分隔符问题,但转换后的NSNumber中的 decimalValue属性提供了错误的值。

let stringValue: String = "8.20"
let nf = NumberFormatter()
nf.locale = Locale(identifier: "en_GB")
nf.usesGroupingSeparator = true
nf.numberStyle = NumberFormatter.Style.decimal
if let number = nf.number(from: stringValue)
{
    let decValue: Decimal = number.decimalValue  // ANSWER: 8.199999999999999
}

I have seen this was discussed many places but haven't seen a fully resolved answer. 我已经看到很多地方都在讨论这个问题,但是还没有一个完全解决的答案。 Would like to hear what the best way to convert a given String value to it's Decimal number considering the Locale. 想知道考虑语言环境将给定String值转换为Decimal数的最佳方法是什么。 (If german / French - group separator is "." and Decimal separator is "," etc) (如果德语/法语-组分隔符为“。”,十进制分隔符为“,”等)

Try this : 尝试这个 :

let stringValue: String = "8.20"

let loc = Locale(identifier: "en_GB")

let nf = NumberFormatter()
nf.locale = loc
nf.usesGroupingSeparator = true
nf.numberStyle = .decimal

var decValue: Decimal? = nil

if let _ = nf.number(from: stringValue) {

    var copy = stringValue

    if let sep = loc.groupingSeparator {
        copy = copy.split(separator: Character(sep)).joined()
    }

    decValue = Decimal(string: copy, locale: loc)
}

And you could check the result this way : 您可以通过以下方式检查结果:

decValue.map { print($0) }  //8.2

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

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