简体   繁体   English

Realm Swift-货币的数据类型

[英]Realm Swift - data type for currency

I've noticed in this question here Using Realm.io to store money values 我在这里使用Realm.io存储货币值时注意到了这个问题

that the recommendation is to use a 'long' data type for currency values in Realm for Android/Java. 建议在Android / Java版Realm中将“长”数据类型用于货币值。

What would the best recommendation be for Swift? 对Swift最好的建议是什么? Convert it to an Int by multiplying by a factor based on the currency? 通过乘以基于货币的因子将其转换为Int? At the moment I'm only dealing with a single currency, but this could theoretically change. 目前,我只使用一种货币,但是从理论上讲这可能会改变。 Precision is obviously important this being a monetary value. 精度显然很重要,因为这是货币价值。

I would recommend using an Int type and then dividing by 100 to convert to cents and multiplying by 100 to store in the Realm. 我建议使用Int类型,然后除以100以将其转换为美分,然后乘以100以存储在Realm中。 The only downside is you won't be able to filter on the moneyWithCents value. 唯一的缺点是您将无法根据moneyWithCents值进行过滤。

class HasMoney: Object {
    private dynamic var money:Int = 0

    var moneyWithCents: Double {
        get {
            return money/100.0
        }
        set {
            money = newValue * 100
        }
    }
}

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

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