如果值没有小数值,则将浮点类型列值转换为整数类型

问题描述 投票:0回答:2

这是我的代码

$data = DB::table('constructor_standings')
    ->join('constructors', 'constructors.constructorId', '=', 'constructor_standings.constructorId')
    ->select('constructor_standings.*', 'constructors.*')
    ->where(['constructor_standings.raceId' => $res2])
    ->orderBy('position', 'asc')
    ->get();

return $data;

constructor_stands 中有一个列 “points”。该列的类型是 float。虽然只有少数值是十进制的,所以我希望其余的值作为整数而不是数字

.0
浮点数返回。

我使用的是Laravel5.8。我怎样才能实现这个目标?

php laravel eloquent floating-point type-conversion
2个回答
0
投票

您可以通过首先检查数字是否为数字(以防万一),然后将其向下舍入并将向下舍入的数字与原始数字进行比较来检查数字是否为小数。如果相同,则不是十进制数。

is_numeric($originalNumber) && floor($originalNumber) != $originalNumber

您可以在回来之前尝试这样的事情:

$data = array_map(function ($value) {
    $value["points"] = is_numeric($value["points"]) && floor($value["points"]) != $value["points"] ? $value["points"] : intval($value["points"]);
    return $value;
}, $data->toArray());

这段代码的作用是对于 $data 中的每个项目,检查“points”索引是否有小数。如果是,则将该值作为整数放回。如果没有,它将返回“点”索引中的原始值。


0
投票

在链式

map()
调用中,通过调用
point
并用点值除以
!fmod()
来确定
1
属性是否没有小数位。如果结果是
0
,那么您可以将 float 类型值显式转换为 int 类型值,而不会丢失任何数据。

return DB::table('constructor_standings')
    ->join('constructors', 'constructors.constructorId', '=', 'constructor_standings.constructorId')
    ->select('constructor_standings.*', 'constructors.*')
    ->where(['constructor_standings.raceId' => $res2])
    ->orderBy('position', 'asc')
    ->get()
    ->map(function($row) {
        if (!fmod($row->point, 1)) {
            $row->point = (int) $row->point;
        }
        return $row;
    });
© www.soinside.com 2019 - 2024. All rights reserved.