When I insert a DOUBLE
, why do I see a value like 9.755046187483832e17
when I select that value? How can I retrieve a number like 97550461874
The double has a precision of about 16 digits. If you need more precision you have two options.
If the value is an integer, you can use bigint
up to about 19 digits of precision.
Better is decimal
which supports up to 65 digits. For instance, the following returns an error:
select format(v*v*v*v*v*v*v*v, 0)
from (select 1001 as v) t
Because the value of v
is treated as a bigint
.
However, the following works very nicely:
select format(v*v*v*v*v*v*v*v, 0)
from (select cast(1001 as decimal(65, 0)) as v) t
Returning 1,008,028,056,070,056,028,008,001
-- which is the precise answer.
If you need precision up to 65 places, then use decimal
. Beyond that, you may have to write your own routines. If you are not doing arithmetic on the field, then consider storing it as a string.
You're probably looking for the FORMAT or ROUND function:
Using FORMAT()
, depending on your locale and your specific needs, you might have to replace the thousands-separator:
mysql> SELECT FORMAT(9.755046187483832e17,0);
975,504,618,748,383,200
mysql> SELECT REPLACE(FORMAT(9.755046187483832e17,0), ',','');
975504618748383200
On the other hand, ROUND()
being a numeric function, it only outputs digits:
mysql> SELECT ROUND(9.755046187483832e17,0);
975504618748383200
See http://sqlfiddle.com/#!2/d41d8/17614 for playing with that.
EDIT: As you noticed, the last two digits are rounded to 00. That's because of DOUBLE precision limits. You have to remember that double are approximate. If you need precise values and/or more digits than available with the 16-bits precision of double, you probably needs to change your column's type to DECIMAL. By default DECIMAL
has 10 digits precision (10 base 10 digits). You could explicitly request up to 65 digits.
For example, if you need up to 20 digits precision, you write something like that:
CREATE TABLE tbl (myValue DECIMAL(20), ...
See http://dev.mysql.com/doc/refman/5.6/en/fixed-point-types.html
Please note however than things are not that simple. Selecting the decimal column might silently convert it to double (or bigint ?) thus loosing the extra precision. You might have to explicitly cast to string in order to preserve the full precision. That means the you might have to deal with that at application level.
create table tbl (dblValue DOUBLE, decValue DECIMAL(20,0));
insert into tbl values (975504618748383289, 975504618748383289);
SELECT dblValue, decValue FROM tbl;
--> DBLVALUE DECVALUE
--> 975504618748383200 975504618748383200
SELECT CAST(dblValue AS CHAR), CAST(decValue AS CHAR) FROM tbl;
--> CAST(DBLVALUE AS CHAR) CAST(DECVALUE AS CHAR)
--> 9.755046187483832e17 975504618748383289
See http://sqlfiddle.com/#!2/d5f58/2 for examples.