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
?
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.
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.
MySQL ROUND() Function The ROUND() function rounds a number to a specified number of decimal places.
Bookmark this question. Show activity on this post.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With