用于保存非常不同的小数位数的列类型

Column type for saving very different number of decimals

我需要像这样存储数字

21000
1.0002
0.00230235
12323235
0.2349523

这是传感器数据,因此保持准确值很重要。 有很多选择。

我的解决方案是将所有值乘以 100 万,并将它们存储为 bigint。这有意义吗?

这是有道理的,但我建议您只使用 decimal 数据类型:https://dev.mysql.com/doc/refman/5.7/en/precision-math-decimal-characteristics.html

如果您要乘以百万,并且如果您收到的数据集的小数点比您预期的多一位,您最终会将该数字乘以 1000 万,然后将所有其他数字乘以 10。相反,使用decimal 数据类型将为您提供小数点右边的 30 个数字。

The declaration syntax for a DECIMAL column is DECIMAL(M,D). The ranges of values for the arguments in MySQL 5.7 are as follows:

M is the maximum number of digits (the precision). It has a range of 1 to 65.

D is the number of digits to the right of the decimal point (the scale). It has a range of 0 to 30 and must be no larger than M.

The SQL standard requires that the precision of NUMERIC(M,D) be exactly M digits. For DECIMAL(M,D), the standard requires a precision of at least M digits but permits more. In MySQL, DECIMAL(M,D) and NUMERIC(M,D) are the same, and both have a precision of exactly M digits.

For a full explanation of the internal format of DECIMAL values, see the file strings/decimal.c in a MySQL source distribution. The format is explained (with an example) in the decimal2bin() function.

要格式化你的数字,你可以像这个答案描述的那样格式化:Format number to 2 decimal places

例子

create table test (
  price decimal(40,20)
);

-- all the above insertions will succeed cleanly
insert into test values (1.5), (1.66), (1.777), (1.12345678901234567890);

-- notice we have 21 digits after decimal
-- MySQL will insert data with 20 decimal and add a warning regarding data truncation
insert into test values (1.123456789012345678901);

数据

select * from test

price
1.50000000000000000000
1.66000000000000000000
1.77700000000000000000
1.12345678901234567890
1.12345678901234567890

select cast(price as decimal(40,2)) from test

price
1.50
1.66
1.78
1.12
1.12