简体   繁体   English

SQLite将文本转换为十进制?

[英]Sqlite convert text to decimal?

I have an Sqlitedb, with a column: amount text not null 我有一个带有列的Sqlitedb: amount text not null

In column amount, I store dollar values in this format: $1.01, $40.58, etc. 在列金额中,我以以下格式存储美元值:$ 1.01,$ 40.58等。

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: 好吧,正如您所说的,这并不是理想的存储值的方式(从一开始就应该以decimal / real格式),但是您可以执行以下操作:

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). SUBSTR方法是一个文本函数,它将获取文本的一部分(在这种情况下,从起始索引开始)。 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). 现在,这应该可以工作,因为SQLLite允许动态类型化 (简而言之,意味着该值用于比较,而不是容器)。

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.) 通过无标度 ,我的意思是$ 1.23将被存储为整数123。(在Java代码中使用long ,在SQL中使用INTEGER 。)

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);

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

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