Encodera

Thanks for reading!

Donate to the site — we work hard for you.

How to convert a string to a number

Short answer

Put the target type in parentheses before the value:

<?php
 
var_dump((int) '42');
var_dump((float) '3.14');

Output:

int(42)
float(3.14)

Checking that a string is a number

User input is worth checking with is_numeric() before converting:

<?php
 
var_dump(is_numeric('42'));
var_dump(is_numeric('3.14'));
var_dump(is_numeric('42abc'));

Output:

bool(true)
bool(true)
bool(false)

Beware of extra characters

A cast does not report an error: it takes the digits at the start of the string and returns zero when there are none.

<?php
 
var_dump((int) '12abc');
var_dump((int) 'abc');

Output:

int(12)
int(0)

Functions used in this recipe

  • round — Rounds a number to a given number of digits.
  • intdiv — Performs integer division.

Thanks for reading!

Donate to the site — we work hard for you.