Home > database >  Converting float value to 2 decimal places in Laravel
Converting float value to 2 decimal places in Laravel

Time:10-12

I have a field on my database called productivity(float) which divides work_time(float) by total_time(float). it work but the output shows up like 0.727273 instead of 0.72. Is there a way in Laravel to fix this?

my controller:

$energy->productivity = $request->input('work_time') / ($request->input('admin_time')   $request->input('driving_time')   $request->input('work_time'));:

my view:

 <td>{{$data->productivity}}</td>

CodePudding user response:

you can use number_format to show the format you want:

it Formats a number with grouped thousands and optionally decimal digits.

$energy->productivity = $request->input('work_time') / ($request->input('admin_time')   $request->input('driving_time')   $request->input('work_time'));
$energy->productivity=number_format($energy->productivity,2);

and you can use it directly in your blade file:

<td>{{number_format($data->productivity, 2)}}</td>

you can replace '2' with any number you want to show more numbers after the comma.

CodePudding user response:

<td>{{round($data->productivity, 2)}}</td>

You can try round

CodePudding user response:

round($data->productivity, 2)

Output: 0.73

sprintf('%0.2f', $data->productivity)

Output: 0.72

Round function will round 0.727273 to 0.73. If you need to just take 2 digits you can use sprintf('%0.2f', $data->productivity) which will output 0.72

  • Related