Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

MySQL decimal fields returned as strings in PHP

By default mysqli returns all values as strings, the MYSQLI_OPT_INT_AND_FLOAT_NATIVE option allows you to convert ints and floats to their appropriate types. Though this does not affect decimal fields.

Is there a way to automatically cast all decimal fields to a php float type without manually calling $value = (float) $row->some_decimal_field?

like image 442
lsjroberts Avatar asked Aug 21 '13 16:08

lsjroberts


People also ask

What is the data type for decimal in MySQL?

In MySQL, NUMERIC is implemented as DECIMAL , so the following remarks about DECIMAL apply equally to NUMERIC . MySQL stores DECIMAL values in binary format. See Section 12.25, “Precision Math”. In this example, 5 is the precision and 2 is the scale.

Can int have decimals MySQL?

MySQL assigns the storage for integer and fractional parts separately. MySQL uses binary format to store the DECIMAL values. It packs 9 digits into 4 bytes. For example, DECIMAL(19,9) has 9 digits for the fractional part and 19-9 = 10 digits for integer part.

How do I get decimal points in MySQL?

MySQL ROUND() Function The ROUND() function rounds a number to a specified number of decimal places.

Can decimal be null in MySQL?

Bookmark this question. Show activity on this post.


1 Answers

I highly doubt it. Decimals use fixed point math, and there is no data type in PHP that can provide this. Floats come close, but they are in fact rounded, meaning that assigning 2 to a float could result in 1.99999999999999999 instead. So even if MySQL offers a way to get a decimal into a PHP float, you are risking loss of data by casting from a decimal to a float.

To handle this cleanly, you'd need something like GMP, but as you can probably guess MySQL can't provide that for you automatically. You will need to do it manually in PHP.

like image 150
Jeroen van den Broek Avatar answered Oct 23 '22 22:10

Jeroen van den Broek