Originally published on php-to-js.learnio.dev — part of the PHP to JavaScript course. View this lesson on the original site.

One number type, many conversion traps

PHP separates int and float. JavaScript uses one number type. Parsing and NaN behave like PHP’s (int) / intval / floatval, with a few gotchas worth seeing side by side.

PHP habit: cast and parse

<?php
$fromCss = (int) '120px';      // 120 in PHP 8+ cast rules — intval is clearer for partial strings
$fromCss = intval('120px');    // 120
$strict = (int) '120';         // 120
$bad = (int) '120px';          // still 120 with intval; (int)'120px' may be 120 depending on context

$pi = 3.14;
$sum = 0.1 + 0.2;              // float surprise in PHP too
var_dump($sum === 0.3);        // false

echo round(4.6), "\n";
echo max(1, 5, 3), "\n";

JavaScript equivalent

const fromCss = parseInt('120px', 10);
const strict = Number('120');
const bad = Number('120px');

console.log('parseInt:', fromCss);
console.log('Number:', strict);
console.log('bad:', bad, Number.isNaN(bad));

const sum = 0.1 + 0.2;
console.log('sum:', sum);
console.log('sum === 0.3:', sum === 0.3);

console.log('round:', Math.round(4.6));
console.log('max:', Math.max(1, 5, 3));
PHP JavaScript When to use
intval('120px') parseInt('120px', 10) Partial numeric strings (CSS, IDs with suffix)
floatval('3.14') parseFloat('3.14') Decimals
(int) '42' / (float) '3.14' Number('42') Whole string must be numeric
is_nan($x) Number.isNaN($x) Prefer Number.isNaN over global isNaN
round($n) Math.round(n)
floor($n) Math.floor(n)
ceil($n) Math.ceil(n)
max($a, $b) Math.max(a, b)
rand($min, $max) Math.floor(Math.random() * (max - min + 1)) + min
$a ** $b a ** b or Math.pow(a, b)

NaN is still typed as number

<?php
var_dump(is_nan(log(-1))); // bool — only true for NaN values
const x = Number('nope');
console.log(Number.isNaN(x));  // true
console.log(typeof x);           // 'number'

Floating point: same class of problem as PHP

console.log(0.1 + 0.2);           // 0.30000000000000004
console.log(0.1 + 0.2 === 0.3); // false

Store money as integer minor units in both ecosystems, or use a decimal library, when exact cents matter.

Try it

Use the amber Try it panel below. Click Run.

const fromCss = parseInt('120px', 10);
const strict = Number('120');
const bad = Number('120px');

console.log('parseInt:', fromCss);
console.log('Number ok:', strict);
console.log('Number bad:', bad, 'isNaN?', Number.isNaN(bad));
console.log('0.1 + 0.2:', 0.1 + 0.2);
console.log('rounded:', Math.round(4.6));

You should see the same patterns you already know from PHP casts and float maths, with stricter Number() and explicit NaN checks.

From PHP to JavaScript — JavaScript Syntax Foundations for PHP Devs