Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

401
Vistas
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 Respuestas
Responde la pregunta

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 Denunciar

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 Denunciar

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 Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda