The lodash method _.toNumber exported as a standalone Node.js module for converting values to numbers.
npx @tessl/cli install tessl/npm-lodash--tonumber@4.0.0The lodash method _.toNumber exported as a standalone Node.js module. This utility provides robust number conversion with support for various input types including strings, booleans, symbols, and objects, with special handling for binary, octal, and hexadecimal string representations.
npm install lodash.tonumberconst toNumber = require('lodash.tonumber');For ES6 modules (with transpilation):
import toNumber from 'lodash.tonumber';const toNumber = require('lodash.tonumber');
// Convert various types to numbers
console.log(toNumber(3.2)); // => 3.2
console.log(toNumber('3.2')); // => 3.2
console.log(toNumber(Number.MIN_VALUE)); // => 5e-324
console.log(toNumber(Infinity)); // => Infinity
// Binary and octal string conversion
console.log(toNumber('0b101')); // => 5
console.log(toNumber('0o7')); // => 7
// Handles edge cases
console.log(toNumber('')); // => 0
console.log(toNumber(' 42 ')); // => 42 (trims whitespace)
console.log(toNumber(null)); // => 0
console.log(toNumber(undefined)); // => NaN
console.log(toNumber(Symbol())); // => NaNConverts any value to a number with comprehensive type coercion and parsing.
/**
* Converts `value` to a number.
*
* @param {*} value The value to process.
* @returns {number} Returns the number.
*/
function toNumber(value);Type Conversion Behavior:
Usage Examples:
const toNumber = require('lodash.tonumber');
// Numeric inputs
toNumber(3.2); // => 3.2
toNumber(Number.MAX_VALUE); // => 1.7976931348623157e+308
toNumber(-42); // => -42
// String inputs
toNumber('123'); // => 123
toNumber('123.45'); // => 123.45
toNumber('0b1010'); // => 10 (binary)
toNumber('0o755'); // => 493 (octal)
toNumber('0xFF'); // => 255 (hexadecimal)
toNumber('-0xFF'); // => NaN (signed hex not supported)
toNumber(' 42 '); // => 42 (whitespace trimmed)
toNumber(''); // => 0 (empty string)
toNumber('abc'); // => NaN (invalid)
// Boolean inputs
toNumber(true); // => 1
toNumber(false); // => 0
// Special values
toNumber(null); // => 0
toNumber(undefined); // => NaN
toNumber(Symbol('test')); // => NaN
// Object inputs with valueOf
const obj = {
valueOf() { return '42'; }
};
toNumber(obj); // => 42
// Object inputs without valueOf
toNumber({}); // => NaN
toNumber([]); // => 0
toNumber([42]); // => 42
toNumber([1, 2]); // => NaNError Handling:
The function never throws errors but returns NaN for values that cannot be converted to valid numbers:
Performance Considerations:
parseInt for binary and octal conversion