Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Turn off scientific notation MySQL

Tags:

mysql

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 975504618748383289 instead?

like image 765
Rose Perrone Avatar asked Aug 03 '13 18:08

Rose Perrone


1 Answers

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.

like image 128
Sylvain Leroux Avatar answered Oct 14 '22 20:10

Sylvain Leroux