gpt4 book ai didi

json - 在快速映射时为变量编写 setter 和 getter 方法?

转载 作者:行者123 更新时间:2023-11-28 06:04:34 25 4
gpt4 key购买 nike

我想在映射时修改 roomTotal 键的值。请引用以下代码:

struct TransactionInfoModel: Codable {
var currencyCode: String
var total: Double
var roomCurrencyCode: String
var exchangeRate: Double

var roomTotal: Double {
get {
let y = (self.roomTotal*100).rounded()/100
return y
}
}
}

最初,roomTotal 键的值来自服务器,如“427.3000000002”,但我想在映射时存储值“427.3”。以上代码无效。

寻找解决问题的建议。

最佳答案

参见 this answer例如,如何舍入 Double 值并返回一个 Decimal 值,该值将保留舍入,而不会在尝试用二进制 float 表示十进制值时产生任何结果交涉。然后,您可以获得四舍五入的 Decimal 值,如下所示:

let roomTotal = 427.3000000002
let value = roomTotal.roundedDecimal(to: 2)

如果你想以指定的小数位数显示它(以及本地化用户当前语言环境的字符串),你可以使用 NumberFormatter:

let formatter = NumberFormatter()
formatter.maximumFractionDigits = 2
formatter.minimumFractionDigits = 2

if let string = formatter.string(for: value) {
print(string)
}

现在,如果你想让 JSONDecoder 为你做这个转换,你可以,但我可能倾向于让 struct 准确地表示返回的内容,避免任何复杂的 init(from:) 实现,但可能包含一个计算属性以以您想要的格式返回值,例如:

struct TransactionInfoModel: Codable {
var currencyCode: String
var total: Double
var roomCurrencyCode: String
var exchangeRate: Double
var roomTotal: Double

var roundedRoomTotal: Decimal {
return roomTotal.roundedDecimal(to: 2)
}
}

如果你在解码时需要舍入 roomTotal,你可以写一个 init(from:) 来做到这一点:

struct TransactionInfoModel: Codable {
var currencyCode: String
var total: Double
var roomCurrencyCode: String
var exchangeRate: Double
var roomTotal: Decimal

init(from decoder: Decoder) throws {
let values = try decoder.container(keyedBy: CodingKeys.self)
currencyCode = try values.decode(String.self, forKey: .currencyCode)
total = try values.decode(Double.self, forKey: .total)
roomCurrencyCode = try values.decode(String.self, forKey: .roomCurrencyCode)
exchangeRate = try values.decode(Double.self, forKey: .exchangeRate)
roomTotal = try values.decode(Double.self, forKey: .roomTotal).roundedDecimal(to: 2)
}
}

或者,您可以省略 init(from:),但在解析后手动将其舍入:

struct TransactionInfoModel: Codable {
var currencyCode: String
var total: Double
var roomCurrencyCode: String
var exchangeRate: Double
var roomTotal: Decimal
}

和:

var object = try! JSONDecoder().decode(TransactionInfoModel.self, from: data)
var rounded = Decimal()
NSDecimalRound(&rounded, &object.roomTotal, 2, .plain)
object.roomTotal = rounded

关于json - 在快速映射时为变量编写 setter 和 getter 方法?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48615492/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com