PHP's intval in TypeScript

✓ Verified: PHP 8.3
Examples tested against actual runtime. CI re-verifies continuously. Only documented examples are tested.
Rosetta Stone: c/atoi · golang/Atoi

How to use

Install via yarn add locutus and import: import { intval } from 'locutus/php/var/intval'.

Or with CommonJS: const { intval } = require('locutus/php/var/intval')

Use a bundler that supports tree-shaking so you only ship the functions you actually use. Vite, webpack, Rollup, and Parcel all handle this. For server-side use this is less of a concern.

Examples

These examples are extracted from test cases that automatically verify our functions against their native counterparts.

#codeexpected result
1intval('Kevin van Zonneveld')0
2intval(4.2)4
3intval(42, 8)42
4intval('09')9
5intval('1e', 16)30
6intval(0x200000001)8589934593
7intval('0xff', 0)255
8intval('010', 0)8

Here's what our current TypeScript equivalent to PHP's intval looks like.

import type { NumericLike, PhpNullish } from '../_helpers/_phpTypes.ts'

type IntvalInput = NumericLike | boolean | PhpNullish

export function intval(mixedVar: IntvalInput, base?: number): number {
// discuss at: https://locutus.io/php/intval/
// parity verified: PHP 8.3
// original by: Kevin van Zonneveld (https://kvz.io)
// improved by: stensi
// bugfixed by: Kevin van Zonneveld (https://kvz.io)
// bugfixed by: Brett Zamir (https://brett-zamir.me)
// bugfixed by: Rafał Kukawski (https://blog.kukawski.pl)
// input by: Matteo
// example 1: intval('Kevin van Zonneveld')
// returns 1: 0
// example 2: intval(4.2)
// returns 2: 4
// example 3: intval(42, 8)
// returns 3: 42
// example 4: intval('09')
// returns 4: 9
// example 5: intval('1e', 16)
// returns 5: 30
// example 6: intval(0x200000001)
// returns 6: 8589934593
// example 7: intval('0xff', 0)
// returns 7: 255
// example 8: intval('010', 0)
// returns 8: 8

let tmp = 0

if (typeof mixedVar === 'boolean') {
return Number(mixedVar)
} else if (typeof mixedVar === 'string') {
if (base === 0) {
const match = mixedVar.match(/^\s*0(x?)/i)
base = match ? (match[1] ? 16 : 8) : 10
}
tmp = Number.parseInt(mixedVar, base || 10)
return Number.isNaN(tmp) || !Number.isFinite(tmp) ? 0 : tmp
} else if (typeof mixedVar === 'bigint') {
return Number(mixedVar)
} else if (typeof mixedVar === 'number' && Number.isFinite(mixedVar)) {
return mixedVar < 0 ? Math.ceil(mixedVar) : Math.floor(mixedVar)
} else {
return 0
}
}

Improve this function

Locutus is a community effort following The McDonald's Theory: we ship first iterations, hoping others will improve them. If you see something that could be better, we'd love your contribution.

View on GitHub · Edit on GitHub · View Raw


« More PHP var functions


Star