四舍五入货币值(SwiftUI,核心数据)

时间:2020-07-17 14:05:10

标签: ios swift core-data swiftui currency

我试图在SwiftUI中创建一个简单的TextField,将提供的值格式化为货币的有效值。我需要将值四舍五入到2位数字。并使用Core Data存储四舍五入的值(这我知道该怎么做,我使用的是Decimal类型,BTW)。

到目前为止,我有这个:

import SwiftUI

struct ContentView: View {
    @State private var newValueAsString = ""
    @State private var value: NSDecimalNumber = 0
    
    let decimalBehavior = NSDecimalNumberHandler(roundingMode: .plain, scale: 2, raiseOnExactness: false, raiseOnOverflow: false, raiseOnUnderflow: false, raiseOnDivideByZero: true)
    
    var body: some View {
        VStack {
            TextField("0", text: $newValueAsString, onCommit: {
                self.value = NSDecimalNumber(string: self.newValueAsString).rounding(accordingToBehavior: self.decimalBehavior)
                print("\(self.value)")
            }
            )
                .multilineTextAlignment(.trailing)
                .font(Font.system(size: 30))
                .keyboardType(.decimalPad)
            
            // Just to test. Later I will save the value to Core Data.
            Text("\(self.value)")
        }
        .padding()
    }
}

struct ContentView_Previews: PreviewProvider {
    static var previews: some View {
        ContentView()
    }
}

问题

当iOS区域使用逗号而不是点(例如,波兰)时,它将无法正常工作。小数键盘有“,”而不是“。”并且当我使用“”时,数字不能正确取整。 123,456变为123。对于使用点的区域(例如,美国),123.456变为预期的123.46。

我在这里想念什么?我的猜测是NumberFormatter,但我无法使其正常工作。

1 个答案:

答案 0 :(得分:2)

NSDecimalNumber可以使用字符串和语言环境进行初始化。 The documentation明确提到语言环境用于解释小数点分隔符(强调我的意思):

语言环境:字典(!),用于定义语言环境(特别是decimalSeparator),用于解释numericString中的数字。

因此您可以执行以下操作:

// Here I am passing the current Locale but you should pass whatever makes sense to your input
self.value = NSDecimalNumber(string: self.newValueAsString, locale: Locale.current).rounding(accordingToBehavior: self.decimalBehavior)

示例:

print(NSDecimalNumber(string: "100.50", locale: Locale(identifier: "en_US"))) // => 100.5
print(NSDecimalNumber(string: "100,50", locale: Locale(identifier: "el_GR"))) // => 100.5