Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the best field definition to store a .NET decimal into MySQL?

I need to store decimals into MySQL, which can have a varying precision. Therefore I would be interested to know which MySQL field type is absolutely equivalent to .NET's decimal structure, if any.

I plan to use Dapper as a lightweight ORM.

like image 942
Erwin Mayer Avatar asked Oct 16 '25 16:10

Erwin Mayer


1 Answers

The .net decimal can be different datatypes under the hood.

.net formats                                  MySQL
----------------------------------------------------
Decimal(Double)                              Float
Decimal(Int32)                               DECIMAL
Decimal(Int32())                             DECIMAL
Decimal(Int64)                               DECIMAL
Decimal(Single)                              DECIMAL
Decimal(UInt32)                              DECIMAL
Decimal(UInt64)                              DECIMAL
Decimal(Int32, Int32, Int32, Boolean, Byte)  DECIMAL
//This is really a UINT96.  

Warning
Note that according to Jon Skeet, decimal can be declared in lots of ways, but will always be a FLOAT under the hood, with all the rounding errors that brings, you have been warned.
See: SQL decimal equivalent in .NET

MySQL's DECIMAL takes up more space if you assign it a larger precision.

From the manual: http://dev.mysql.com/doc/refman/5.5/en/precision-math-decimal-changes.html

Values for DECIMAL columns in MySQL 5.5 are stored using a binary format that packs nine decimal digits into 4 bytes.

The largest number of digits is 65, divided by 9 = 8 bytes, an INT128.

like image 67
Johan Avatar answered Oct 18 '25 05:10

Johan