PHP's intval in JavaScript

How to use

You you can install via yarn add locutus and require this function via const intval = require('locutus/php/var/intval').

It is important to use a bundler that supports tree-shaking so that you only ship the functions that you actually use to your browser, instead of all of Locutus, which is massive. Examples are: Parcel, webpack, or rollup.js. For server-side use this is typically less of a concern.

Examples

Please note that these examples are distilled from test cases that automatically verify our functions still work correctly. This could explain some quirky ones.

#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 JavaScript equivalent to PHP's intval looks like.

module.exports = function intval(mixedVar, base) {
// discuss at: https://locutus.io/php/intval/
// 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, match

const type = typeof mixedVar

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

A community effort

Not unlike Wikipedia, Locutus is an ongoing community effort. Our philosophy follows The McDonald’s Theory. This means that we assimilate first iterations with imperfections, hoping for others to take issue with-and improve them. This unorthodox approach has worked very well to foster fun and fruitful collaboration, but please be reminded to use our creations at your own risk. THE SOFTWARE IS PROVIDED "AS IS" has never been more true than for Locutus.

Now go and: [ View on GitHub | Edit on GitHub | View Raw ]


« More PHP var functions


Star