Using Realm.io to store money values

前端 未结 4 1456
被撕碎了的回忆
被撕碎了的回忆 2021-01-18 09:11

I\'m starting to play with Realm.io in an Android app that I\'m writing. In one of my data objects, I\'m required to store a currency value. Previously I had stored the valu

4条回答
  •  后悔当初
    2021-01-18 09:51

    What I do is store it as long

    I have defined in my application a constant like so:

    public static final BigDecimal MONEY_PRECISION = new BigDecimal(1000);
    

    and when I need to store a big decimal it goes like this:

    public class MoneyClass extends RealmObject {
        long _price = 0;
    
        public void set_price(BigDecimal price) {
            this._price = price.longValue() * App.MONEY_PRECISION.longValue();
        }
    
        public BigDecimal get_price() {
           return new BigDecimal(_price).divide(App.MONEY_PRECISION, 0, 0);
        }
    
    }
    

    In theory this should be faster than saving it on strings , but I haven't really looked at the realm code much

提交回复
热议问题