How to format value in php?

-4

I have the following code

<?php
ini_set('display_errors', true);
error_reporting(E_ALL);

include_once("con.php");

$pdo = conectar();

$id_empresa = $_GET['id_empresa'];
$data = $_GET['data'];

$tipo = "ENT";
$valorTotalE = 0;

$valorTotalEntradas=$pdo->prepare('SELECT valor FROM importa
                                                        WHERE data=:data
                                                        AND id_empresa=:id_empresa
                                                        AND tipo=:tipo');

$valorTotalEntradas->bindValue('id_empresa', $id_empresa);
$valorTotalEntradas->bindValue('data', $data);
$valorTotalEntradas->bindValue('tipo', $tipo);
$valorTotalEntradas->execute();

while ($linha=$valorTotalEntradas->fetch(PDO::FETCH_ASSOC)) {

    $valor = $linha['valor'];
    $valorTotalE = $valorTotalE + $valor;

    $valorTotalE = number_format($valorTotalE,2,',','.');

    $return = array(
        'valorTotalE' => $valorTotalE
    );

}

echo json_encode($return);
?>

This command line "$ valueTotalE = number_format ($ valueTotalE, 2, ',', '.');" format the value at 9.999.99, however, it does that which appears in the image below

    
asked by anonymous 26.12.2017 / 20:27

1 answer

2

The problem is that you are trying to add after using number_format , this does not make sense, you can only add any number like casting strings or types int , float , and bool

See if you do this you will get the error:

<?php

$valor1 = 'foo';
$valor2 = '2';
$valor3 = '3';

$total = $valor1 * $valor2 * $valor3;

In other words, the message indicates that you are trying to perform a math operation without having a valid number:

  

Notice: A well-formed numeric value encountered

Just use number_format after:

while ($linha=$valorTotalEntradas->fetch(PDO::FETCH_ASSOC)) {

    $valor = $linha['valor'];
    $valorTotalE = $valorTotalE + $valor;

}

//Aqui você usa o number_format
$valorTotalE = number_format($valorTotalE, 2, ',', '.');

echo json_encode(array(
    'valorTotalE' => $valorTotalE
));

Note that for this to work in the database you should use DECIMAL in the column valor , if you use varchar and the format is not numeric it is able to fail too.

    
26.12.2017 / 21:05