zeroonnet
zeroonnet

Reputation: 303

php round number - When echo it displays 2 decimals, if print to CSV it displays .0999999

Using http://www.maatwebsite.nl/laravel-excel/ to export to CSV and Excel.

I have a $rows array which contains all rows with its columns.

Some columns have a formatted number using number_format(round((float)$number, 2 ), 2, '.', ''); This $number is a column from a query result.

If I var_dump $rows every number is well formatted.

When I do

 Excel::create($filename, function($excel) use ($rows) {
    $excel->sheet('Sheet 1', function($sheet) use ($rows) {
        $sheet->rows($rows);
    });
})->export('csv');

it exports to CSV (same happens if I choose excel) and some columns display numbers wrongly like 82.70999999999999 instead of 82.71

Can't find a way to fix this

Upvotes: 2

Views: 1811

Answers (1)

Teocci
Teocci

Reputation: 8945

when you format the column try this straight forward solution:

$number = 82.70999999999999; $float_string = sprintf("%.2f", $number); // $float_string = "82.71";

That will replace your number_format(round((float)$number, 2 ), 2, '.', '');

Hope it helps~!

Upvotes: 0

Related Questions