What solution to the error: "A non well Formed Numeric value encountered"?

Asked

Viewed 13,026 times

0

   function exemplo() {

    $premio = "Jose ganhou na lotérica 2.000.000,00 mais gastou 
    1.000.000,00 com quanto josé ficou? <br>";

    echo $premio;

    $smtNumero = explode('na lotérica ',$premio);
    $primeiroArray = explode(' mais gastou 1.000', $smtNumero[1]);


    $outroExplode = explode('0 mais gastou ', $premio);
    $segundoF = explode(' com quanto josé ficou?', $outroExplode[1]);

    unset($primeiroArray[1]);
    unset($segundoF[1]);

    $final1 = str_replace (',', '.', $primeiroArray[0]);
    $final2 = str_replace (',', '.', $segundoF[0]);

    $soma = ($final1 - $final2);

    echo $soma;

}

exemplo();

As already mentioned, the code returns:

"A non well Formed Numeric value encountered"

How to fix this error?

  • https://stackoverflow.com/questions/20574465/date-method-a-non-well-formed-numeric-value-encountered-does-not-want-to-fo It would help you?

1 answer

1

The problem in your code is occurring due to variable $final1 is receiving a string as value, thus generating error at the time of calculation, it is receiving this value: 2.000.000.00 mais gastou 1.000.000.00 com quanto josé ficou?, so it wouldn’t work properly,

I don’t quite understand what the purpose of this code is, it’s certainly for studies, so I’m going to try to dissect, my answer, (that was a little different from your), okay!

function exemplo() {

    $premio = "Jose ganhou na lotérica 2.000.000,00 mais gastou 1.000.000,00 com quanto josé ficou? <br>";

    echo($premio);

    $primeiro_valor = substr($premio, 25, 12);
    $segundo_valor = substr($premio, 50, 12);    

    $final1 = str_replace (',', '.', str_replace ('.', '', $primeiro_valor));
    $final2 = str_replace (',', '.', str_replace ('.', '', $segundo_valor));

    $soma = ($final1 - $final2);

    echo $soma;

}

exemplo();

Instead of using the explode(); I chose to use the substr();, that in my view fits better your case, with it I determined the starting point and the amount of characters I wanted, after that I used the str_replace(); to remove the "." and change the "," for ".", why?

Because in php you use the dot, and in your previous logic you were just swapping the commas for dots, so, swapping 1.000.000,00 for 1.000.000.00 this in php would basically become the numeral 1, because the correct number, for the calculation of "one million" would be 1000000.00, after dealing with the numbers I just made a sum and ready.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.