MySQL decimal fields returned as strings in PHP

帅比萌擦擦* 提交于 2019-12-06 03:42:56

问题


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?


回答1:


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.




回答2:


Here is something that you can do with PHP to solve the problem:

function string_to_float($foo){
    if($foo*1==$foo && !empty($foo)){
        return $foo*1;
    } else {
        return $foo;
    }
}

string_to_float($row->some_decimal_field);

The real question is, Why do you need to convert the type of the decimal string? If you are trying to use it in math, php will make the conversion automatically for you. As a decimal string is equivalent to a float with the same value. Here is a simple test:

$foo = "1.2";
$bar = 1.2;


if($foo===$bar){
  $equivalent = "is";
} else {
  $equivalent = "is not";
}

print '"1.2" '.$equivalent.' equal to 1.2 in type and value<br />';

if($foo==$bar){
  $equivalent = "is";
} else {
  $equivalent = "is not";
}

print '"1.2" '.$equivalent.' equal to 1.2 in value<br />';

$foo = "1.2"*1;
$bar = 1.2;

if($foo===$bar){
  $equivalent = "is";
} else {
  $equivalent = "is not";
}

print '"1.2"*1 '.$equivalent.' equal to 1.2 in type and value<br />';

which will return:

"1.2" is not equal to 1.2 in type and value
"1.2" is equal to 1.2 in value
"1.2"*1 is equal to 1.2 in type and value


来源:https://stackoverflow.com/questions/18362598/mysql-decimal-fields-returned-as-strings-in-php

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!