How can I store a BigDecimal (Java) value in a Real (SQlite) column?

前端 未结 3 2204
星月不相逢
星月不相逢 2020-12-17 04:09

I\'m still having big problems with BigDecimal (the trail of tears started here, and continued to here so far.

Now I\'ve got the opposite problem - going from BigDec

相关标签:
3条回答
  • 2020-12-17 04:38

    I use the SQLite Integer type and convert like so:

    BigDecimal bd = new BigDecimal("1234.5678");
    
    int packedInt = bd.scaleByPowerOfTen(4).intValue(); // packedInt now = 12345678
    

    Now save packedInt to SQLite Integer field.

    To go back to BigDecimal:

    BigDecimal bd = new BigDecimal(packedInt); // bd = 12345678
    
    bd = bd.scaleByPowerOfTen(-4);             // now bd = 1234.5678
    
    0 讨论(0)
  • 2020-12-17 04:39

    So how can I manipulate the BigDecimal value in the so that it will be accepted by the ContentValues instance?

    Well, you can call doubleValue() on the BigDecimal to downgrade it to a double, which can go in the ContentValues (after autoboxing it to a Double). Or, you can store its string representation in a TEXT column. Or, you can store the unscaledValue() and scale() in two INTEGER columns.

    But SQLite's closest match is REAL

    No, it is not.

    You seem to be interested in storing pricing data in SQLite. A search for storing prices in sqlite on a major search engine turns up:

    • SQLite how to use integer for storing price value
    • Storing currency values in SQLite3
    • https://dba.stackexchange.com/questions/15729/storing-prices-in-sqlite-what-data-type-to-use

    The consensus is to store the value as an INTEGER column, priced in the smallest individual currency unit (e.g., cents for currency values in US dollars), or something else as appropriate (e.g., tenths of a cent if that's the finest granularity of the prices).

    Your POJO would then hold int values to match.

    0 讨论(0)
  • 2020-12-17 04:55

    There's two possibilities:

    1. Store it as a String.
    2. Store it as a Blob. BigDecimal is Serializable, so this should work.

    The first should be straightforward, for the second I'd point you to an excellent question on a similar subject, how to store Image as blob in Sqlite & how to retrieve it?

    0 讨论(0)
提交回复
热议问题