Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

392
Visualizações
Addition to number formed using number_format() php function

When i try to add a integer to 3 digit number formed using php number_format() function give right result but when number become 4 digit it give wrong output.

I have tried this. please explain me the reason behind this??

$num1=number_format(1000.5,2);
$num1+=1;
echo $num1;

Output:2

But

  $num1=number_format(100.5,2);
  $num1+=1;
  echo $num1."\n";`

Output:101.5

enter image description here

enter image description here

over 4 years ago · Santiago Trujillo
3 Respostas
Responde à pergunta

0

number_format() returns a string not a number. It is there to format a numeric type (integer, float) to a string with a specific, desired "layout". So what you do is add the number 1 to the string resulting from number_format, which will try to cast the string back to a number, apparently resulting in 1 for the string cast as well, which gives you 2 total.

tl;dr; Do calculations on numbers only and then do number_format at the very end to output in a defined format.

over 4 years ago · Santiago Trujillo Relatório

0

$num1 = number_format(1000.5, 2);
var_dump($num1);
// => string(8) "1,000.50"

$num1 += 1;
var_dump($num1);
// => int(2)

Function number_format() returns string.

And that string is type cast to integer when you are adding 1

See Type Juggling

over 4 years ago · Santiago Trujillo Relatório

0

The quickest solution would be using str_replace() on your formatted number. Something like this would do:

(float)str_replace( ',', '', $formatted_number )

By removing the commas from the string and asking for the float value, you'll get a usable number.

over 4 years ago · Santiago Trujillo Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda