以 bigint 形式存储在 sqlite 中的货币(加密货币)的数学运算
math operations on currencies (crypto) stored in sqlite as bigint
我正在尝试将加密货币值存储在 sqlite 数据库中。
我读到将这些值存储为 float 或 double 是不正确的,因为 IEEE754.
出于这个原因,我在我的数据库中将这些值保存为 biginteger。 (在读取或存储值之前,我在我的应用程序中乘以或除以 10^8 或 10^(-8))。
create table Transactions
(
id INTEGER not null primary key autoincrement unique,
crypto_name TEXT not null,
total_fiat_amount BIGINT default 0 not null,
crypto_fiat_price BIGINT default 0 not null,
commission BIGINT default 0 not null,
date BIGINT not null
);
但现在我有一个问题:假设我想用这个公式计算硬币的数量:
SELECT "coin_name", ("total_fiat_amount"-"commission")/("crypto_fiat_price")) AS crypto_amount FROM Transactions GROUP BY "coin_name";
但结果总是错误的,因为它总是整数(小数部分总是被截断和省略)。我需要一个实数,但又不失精度,因为我需要负担得起的结果。
作为变通方法,我可以转换为 1.0 的双倍或乘法,但这不是我想要的,因为这样做我认为我会得到错误的双倍结果! (所以我可以从一开始就使用 double)。
有什么可行的解决方案吗?
(除非避免 sql 进行此类计算并在应用程序中进行数学计算,因为这不是有效的解决方案)
关键是只乘被除数而不是乘以结果。
如果total_fiat_amount-commission
和crypto_fiat_price
都是逗号后最多两位数字的单值,则不需要同时乘以10^8,只需乘以10^2。
在这种情况下,结果将精确到逗号后的小数点后 0 位。
如果你想在逗号后有8位小数精度,你可以在运行除法前用10^8乘除数。
如果您以美分存储 total_fiat_amount
、commission
和 crypto_fiat_price
,您可以使用:
SELECT "coin_name", (("total_fiat_amount"-"commission")*100000000)/("crypto_fiat_price")) AS crypto_amount FROM Transactions GROUP BY "coin_name";
这将 total_fiat_amount-commission
限制为 64 位整数限制除以 10^8,因此 total_fiat_amount-commission
的最大限制为 92233720368
(美分)。
我正在尝试将加密货币值存储在 sqlite 数据库中。 我读到将这些值存储为 float 或 double 是不正确的,因为 IEEE754. 出于这个原因,我在我的数据库中将这些值保存为 biginteger。 (在读取或存储值之前,我在我的应用程序中乘以或除以 10^8 或 10^(-8))。
create table Transactions
(
id INTEGER not null primary key autoincrement unique,
crypto_name TEXT not null,
total_fiat_amount BIGINT default 0 not null,
crypto_fiat_price BIGINT default 0 not null,
commission BIGINT default 0 not null,
date BIGINT not null
);
但现在我有一个问题:假设我想用这个公式计算硬币的数量:
SELECT "coin_name", ("total_fiat_amount"-"commission")/("crypto_fiat_price")) AS crypto_amount FROM Transactions GROUP BY "coin_name";
但结果总是错误的,因为它总是整数(小数部分总是被截断和省略)。我需要一个实数,但又不失精度,因为我需要负担得起的结果。
作为变通方法,我可以转换为 1.0 的双倍或乘法,但这不是我想要的,因为这样做我认为我会得到错误的双倍结果! (所以我可以从一开始就使用 double)。
有什么可行的解决方案吗? (除非避免 sql 进行此类计算并在应用程序中进行数学计算,因为这不是有效的解决方案)
关键是只乘被除数而不是乘以结果。
如果total_fiat_amount-commission
和crypto_fiat_price
都是逗号后最多两位数字的单值,则不需要同时乘以10^8,只需乘以10^2。
在这种情况下,结果将精确到逗号后的小数点后 0 位。
如果你想在逗号后有8位小数精度,你可以在运行除法前用10^8乘除数。
如果您以美分存储 total_fiat_amount
、commission
和 crypto_fiat_price
,您可以使用:
SELECT "coin_name", (("total_fiat_amount"-"commission")*100000000)/("crypto_fiat_price")) AS crypto_amount FROM Transactions GROUP BY "coin_name";
这将 total_fiat_amount-commission
限制为 64 位整数限制除以 10^8,因此 total_fiat_amount-commission
的最大限制为 92233720368
(美分)。