简体   繁体   中英

Sqlite convert text to decimal?

I have an Sqlitedb, with a column: amount text not null

In column amount, I store dollar values in this format: $1.01, $40.58, etc.

I'm trying to sum up the dollar values using

SELECT SUM(amount) FROM record WHERE date LIKE '"+date+"'"

However, it doesn't work, presumably because you can't add text. I know this isn't the ideal storage but how would I go about parsing the amounts so that I can add them up?

Well, as you have stated this is far from the ideal way to store the values (which should be in decimal / real format from the start), however you could do something like this:

SELECT SUM(SUBSTR(amount, 2)) FROM record WHERE date LIKE '"+date+"'"

The SUBSTR method is a text function that will take a section of the text (in this case, from a starting index). The problem here was the $ sign, which was confused the dynamic type conversion into believing you were trying to add strings together.

This should now work as SQLLite allows for dynamic typing (which in a nutshell, means that the value is used for comparison, not the container).

It's much better to store the amounts as unscaled integers, and just format them when needed for display. You get more compact storage, and easier and faster addition. Using integers avoids the risk of rounding errors in floating-point representations.

By unscaled , I mean $1.23 would be stored as the integer 123. (Use long in your Java code, and INTEGER in the SQL.)

You can format amounts for display by querying the locale for the relevant info:

// implement this any way you like!
long         amount   = getAmountFromDb();    

// use default locale if you want
Locale       locale       = getLocaleFromSomewhere();                 
Currency     currency     = Currency.getInstance(locale);
NumberFormat format       = NumberFormat.getCurrencyInstance(locale);
int          scale        = currency.getDefaultFractionDigits();

BigDecimal   scaledAmount = new BigDecimal(unscaledBalance).movePointLeft(scale);
String       textAmount   = format.format(scaledAmount);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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