简体   繁体   English

在带有SDK Paypal的Swift 3中键入NSDecimalNumber

[英]Type NSDecimalNumber in swift 3 with sdk paypal

When I am creating the item to send to paypal I do the following 当我创建要发送给贝宝的物品时,请执行以下操作

let ammountRequest: String = txtAmmount.text!
let item = PayPalItem(name: "shop things", withQuantity: 1, withPrice: NSDecimalNumber(string: ammountRequest), withCurrency: "EUR", withSku: "Create Balance")

let items = [item]
let subtotal = PayPalItem.totalPrice(forItems: items)

If the "ammountRequest" equals 11.12 for example, on the page to pay will appear the 11 instead of the 11.12 as Can I do to appear the decimal places since they are being removed? 例如,如果“ ammountRequest”等于11.12,则在付款页面上将显示11而不是11.12,因为删除后我可以显示小数位吗?

You are probably not dealing well with localization. 您可能无法很好地应对本地化。 NSDecimalNumber(string: ammountRequest) is trying to parse the string using the current locale. NSDecimalNumber(string: ammountRequest)尝试使用当前语言环境解析字符串。 Therefore you have to be sure that the string contains , (comma) or . 因此,您必须确保该字符串包含, (逗号)或. (point) as the decimal separator depending on the current locale. (点)作为小数点分隔符,具体取决于当前的语言环境。

The discussion in the documentation describes the accepted values depending on locale. 文档中的讨论描述了根据区域设置而接受的值。

One way to deal with this is to replace all possible decimal separators ( . and , ) with . 解决此问题的一种方法是将所有可能的十进制分隔符( ., )替换为. and then use English locale (ideally the POSIX locale): 然后使用英语语言环境(最好是POSIX语言环境):

let amountString = "11.12"
let normalizedAmountString = amountString.replacingOccurrences(of: "[,.]", with: ".", options: .regularExpression)

let posixLocale = Locale(identifier: "en_US_POSIX")

let amount = NSDecimalNumber(string: normalizedAmountString, locale: posixLocale)
print(amount)

Note that most of the times NSDecimalNumber can deal with both . 请注意,大多数时候NSDecimalNumber可以同时处理这两种情况. and , . 并且, The problems appear when . 问题出现在. or , is a grouping separator in the current locale. 或者,是在当前地区的分组分离器。

PS: You should use Decimal instead of NSDecimalNumber in Swift code. PS:您应该在Swift代码中使用Decimal而不是NSDecimalNumber

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

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