Probably your error log level is not displaying Warnings and / or Notices, but if it were enabled maybe it would display this notification in the middle of the page:
Notice: A well-formed numeric value encountered in ... on line 34
You have to understand that a thing is a number, even if it is a string, its format must be a number that the machine understands .
For example, if you do this:
<?php
$valor1 = '100foo';
$valor2 = '2';
$total = $valor1 / $valor2;
var_dump($total);
This is returned to me:
PHP Notice: A non well formed numeric value encountered in C:\Users\guilherme\foo.php on line 6
int(50)
See that you've even managed to split 100 by 2 = int(50)
, this is because PHP tries to parse the string, but if it does something more complicated like:
<?php
$valor1 = '100.000,00';
$valor2 = '2';
$total = $valor1 / $valor2;
var_dump($total);
You will return this:
PHP Notice: A non well formed numeric value encountered in C:\Users\guilherme\Desktop\debug.php on line 7
float(50)
The result that PHP tried to parse and displayed, but only acknowledged 100.000
, which is "pretty much the same 100.0
, ie a type float
, and split it like this 100.0/2
= float(50)
That is, 100.000,00
to the machine (independent of any language) is not a number, it is just string
, in other languages outside PHP (which tries to parse ) is able to occur exception or fatal errors when trying something like "100.000,00"/5
How to turn money format into a number?
First I really recommend that instead of using VARCHAR
or CHAR
in your bank you'd prefer to use DECIMAL
and work with real numbers, because if your bank is returning something like this 100.000,00
it's because of certainty is a type of CHAR
that it uses, please do not use something like:
ALTER TABLE 'minha_tabela' MODIFY 'minha_culuna' DECIMAL(8,2)
Before changing the values of each line, if you do this without changing you can be sure that it will break all the data, which will be impossible to reverse, first convert the existing rows, for example 100.000,00
should be '100000.00 , manually or with a script that traverses all rows in the table.
Now if you really want to insist on using CHAR
( VARCHAR
or TEXT
) then palliatively you can try using function like this:
function reverse_number_format($str)
{
if (is_numeric($str)) {
return $str;
} elseif (preg_match('#^(.*?)[.,\s](\d{2})$#', $str, $out)) {
return preg_replace('#\D#', '', $out[1]) . '.' . $out[2];
}
return false;
}
And then use that in your script:
round(reverse_number_format($c) / reverse_number_format($result->valorsc), 5);
Note: But as I said, this is a palliative solution , it is recommended to change its structure.