I think it is much better to simply look at the _.toNumber source and that would practically answer your question:

function toNumber(value) {
  if (typeof value == 'number') {
    return value;
  }
  if (isSymbol(value)) {
    return NAN;
  }
  if (isObject(value)) {
    var other = typeof value.valueOf == 'function' ? value.valueOf() : value;
    value = isObject(other) ? (other + '') : other;
  }
  if (typeof value != 'string') {
    return value === 0 ? value : +value;
  }
  value = value.replace(reTrim, '');
  var isBinary = reIsBinary.test(value);
  return (isBinary || reIsOctal.test(value))
    ? freeParseInt(value.slice(2), isBinary ? 2 : 8)
    : (reIsBadHex.test(value) ? NAN : +value);
}

As you can see it does a bunch of other things in comparison to parseInt. To be more specific:

console.log(_.toNumber(1),       parseInt(1))        // same 
console.log(_.toNumber('1'),     parseInt('1'))      // same  
console.log(_.toNumber('b'),     parseInt('b'))      // same  
console.log(_.toNumber({}),      parseInt({}))       // same 
console.log(_.toNumber(' 1 '),   parseInt(' 1 '))    // same
console.log(_.toNumber([1]),     parseInt([1]))      // same
console.log(_.toNumber(' 1a1 '), parseInt(' 1a1 '))  // NaN      1
console.log(_.toNumber([1,2]),   parseInt([1,2]))    // NaN      1
console.log(_.toNumber(false),   parseInt(false))    // 0        NaN
console.log(_.toNumber(!0),      parseInt(!0))       // 1        NaN
console.log(_.toNumber(!!0),     parseInt(!!0))      // 0        NaN
console.log(_.toNumber(5e-324),  parseInt(5e-324))   // 5e-324   5
console.log(_.toNumber(5.5),     parseInt(5.5))      // 5.5      5
console.log(_.toNumber(null),    parseInt(null))     // 0        NaN
console.log(_.toNumber(Infinity),parseInt(Infinity)) // Infinity NaN
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.11/lodash.min.js"></script>

So to summarize _.isNumber gives you more expected / consistent and I would argue safer results when it comes to parsing input with arrays, decimals, falsy values and strings. It would check the entire input vs parseInt which only cares about the first valid value as you can see from the examples above. It also handles better the negate operator (!) etc.

So overall it does have its uses vs parseInt

Note: What is a gotcha here is that both _.toNumber and parseInt return NaN for undefined which considering how _.toNumber deals with the rest of the falsy values one would expect to return 0 vs NaN:

console.log(_.toNumber(undefined), parseInt(undefined))  // NaN NaN
Answer from Akrion on Stack Overflow
Top answer
1 of 2
19

I think it is much better to simply look at the _.toNumber source and that would practically answer your question:

function toNumber(value) {
  if (typeof value == 'number') {
    return value;
  }
  if (isSymbol(value)) {
    return NAN;
  }
  if (isObject(value)) {
    var other = typeof value.valueOf == 'function' ? value.valueOf() : value;
    value = isObject(other) ? (other + '') : other;
  }
  if (typeof value != 'string') {
    return value === 0 ? value : +value;
  }
  value = value.replace(reTrim, '');
  var isBinary = reIsBinary.test(value);
  return (isBinary || reIsOctal.test(value))
    ? freeParseInt(value.slice(2), isBinary ? 2 : 8)
    : (reIsBadHex.test(value) ? NAN : +value);
}

As you can see it does a bunch of other things in comparison to parseInt. To be more specific:

console.log(_.toNumber(1),       parseInt(1))        // same 
console.log(_.toNumber('1'),     parseInt('1'))      // same  
console.log(_.toNumber('b'),     parseInt('b'))      // same  
console.log(_.toNumber({}),      parseInt({}))       // same 
console.log(_.toNumber(' 1 '),   parseInt(' 1 '))    // same
console.log(_.toNumber([1]),     parseInt([1]))      // same
console.log(_.toNumber(' 1a1 '), parseInt(' 1a1 '))  // NaN      1
console.log(_.toNumber([1,2]),   parseInt([1,2]))    // NaN      1
console.log(_.toNumber(false),   parseInt(false))    // 0        NaN
console.log(_.toNumber(!0),      parseInt(!0))       // 1        NaN
console.log(_.toNumber(!!0),     parseInt(!!0))      // 0        NaN
console.log(_.toNumber(5e-324),  parseInt(5e-324))   // 5e-324   5
console.log(_.toNumber(5.5),     parseInt(5.5))      // 5.5      5
console.log(_.toNumber(null),    parseInt(null))     // 0        NaN
console.log(_.toNumber(Infinity),parseInt(Infinity)) // Infinity NaN
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.11/lodash.min.js"></script>

So to summarize _.isNumber gives you more expected / consistent and I would argue safer results when it comes to parsing input with arrays, decimals, falsy values and strings. It would check the entire input vs parseInt which only cares about the first valid value as you can see from the examples above. It also handles better the negate operator (!) etc.

So overall it does have its uses vs parseInt

Note: What is a gotcha here is that both _.toNumber and parseInt return NaN for undefined which considering how _.toNumber deals with the rest of the falsy values one would expect to return 0 vs NaN:

console.log(_.toNumber(undefined), parseInt(undefined))  // NaN NaN
2 of 2
3

_.toNumber converts a given input to a number if such a conversion is possible, otherwise returns NaN. The parseInt and parseFloat methods also work in same manner (the former will only return integers though), however, they are much more lax in their parsing rules. _.toNumber is significantly more restrictive.

For eg, with same input '5.2a', parseInt would return 5, parseFloat would return 5.2, and _.toNumber would return NaN. The former two ignore everything after the first unrecognised character and return the number formed by all parsed characters till that point. The last one however returns NaN if an unrecognised character is encountered.

_.toNumber is comparable and functionally same to Number function.

🌐
GitHub
github.com › lodash › lodash › issues › 2023
Feature Request: _.parseFloat :) · Issue #2023 · lodash/lodash
lodash / lodash Public · Notifications · You must be signed in to change notification settings · Fork 7.1k · Star 60.1k · New issueCopy link · New issueCopy link · Closed · Closed · Feature Request: _.parseFloat :)#2023 · Copy link · Labels · enhancementvotes needed ·
🌐
MeasureThat
measurethat.net › Benchmarks › Show › 5553 › 0 › lodashround-vs-tofixed-vs-tofixed-and-parsefloat
Benchmark: lodash.round VS toFixed() VS toFixed() and parseFloat - MeasureThat.net
lodash.round VS toFixed() VS parseFloat().toFixed() lodash.round VS toFixed() wth parseint · lodash.round VS Math.round (divide by 0) lodash.round VS toFixed() VS toFixed() and Number · Comments · × · Do you really want to delete benchmark? Cancel Delete ·
🌐
Lodash
lodash.com › docs
Lodash Documentation
Creates an array of values by running each element in collection thru iteratee. The iteratee is invoked with three arguments: (value, index|key, collection). Many lodash methods are guarded to work as iteratees for methods like _.every, _.filter, _.map, _.mapValues, _.reject, and _.some.
🌐
Hotexamples
javascript.hotexamples.com › examples › lodash › - › parseFloat › javascript-parsefloat-function-examples.html
JavaScript parseFloat Examples, lodash.parseFloat JavaScript Examples - HotExamples
_.each(schema, function(val, key) { if (!_.has(body, key)) { return; } if (val === 'integer') { // Perform `parseInt` on all integers body[key] = _.parseInt(body[key]); } else if (val === 'float') { // Perform `parseFloat` on all integers body[key] = _.parseFloat(body[key]); } }.bind(this));
🌐
Justinhelmer
justinhelmer.github.io › lodash.github.io › docs › 4.5.1 › lodash.js.html
lodash.js - Documentation
*/ var stringEscapes = { '\\': '\\', "'": "'", '\n': 'n', '\r': 'r', '\u2028': 'u2028', '\u2029': 'u2029' }; /** Built-in method references without a dependency on `root`. */ var freeParseFloat = parseFloat, freeParseInt = parseInt; /** Detect free variable `exports`. */ var freeExports = (objectTypes[typeof exports] && exports && !exports.nodeType) ?
🌐
GeeksforGeeks
geeksforgeeks.org › javascript › lodash-_-tonumber-method
Lodash _.toNumber() Method - GeeksforGeeks
October 25, 2023 - // Requiring the lodash library const _ = require("lodash"); // Use of _.toNumber() method console.log(_.toNumber(15.6)); console.log(_.toNumber('15.6'));
🌐
Dead Simple Chat
deadsimplechat.com › blog › 5-ways-to-convert-string-to-a-number-in-javascript
5 Ways to Convert String to a Number in JavaScript
July 6, 2024 - let inputString = "100Something"; let number = parseFloat(inputString); // number will be 100
Find elsewhere
🌐
W3Schools
w3schools.com › jsref › jsref_parsefloat.asp
JavaScript parseFloat() Method
The parseFloat() method parses a value as a string and returns the first number.
🌐
GitHub
github.com › lodash › lodash › › issues › 5216
lodash/lodash
April 17, 2021 - isNumber (value) { return !_.isNaN(parseFloat(value)) && _.isNumber(parseFloat(value)); }
Author   stanley85
🌐
GeeksforGeeks
geeksforgeeks.org › javascript › lodash-_-parseint-method
Lodash _.parseInt() Method - GeeksforGeeks
November 3, 2023 - // Requiring the lodash library const _ = require("lodash"); // Use of _.parseInt() method console.log(_.parseInt("10.33")); console.log(_.parseInt("8", 8)); console.log(_.parseInt("100", 10));
🌐
MeasureThat
measurethat.net › Benchmarks › Show › 6547 › 0 › lodashround-vs-tofixed-vs-parsefloattofixed
Benchmark: lodash.round VS toFixed() VS parseFloat().toFixed() - MeasureThat.net
lodash.round VS toFixed() VS toFixed() and parseFloat · lodash.round VS toFixed() wth parseint · lodash.round VS Math.round (divide by 0) lodash.round VS toFixed() VS toFixed() and Number · Comments · × · Do you really want to delete benchmark? Cancel Delete ·
Top answer
1 of 5
67

The internal workings are not that different, as @James Allardic already answered. There is a difference though. Using parseFloat, a (trimmed) string starting with one or more numeric characters followed by alphanumeric characters can convert to a Number, with Number that will not succeed. As in:

parseFloat('3.23abc'); //=> 3.23
Number('3.23abc'); //=> NaN

In both conversions, the input string is trimmed, by the way:

parseFloat('  3.23abc '); //=> 3.23
Number('   3.23 '); //=> 3.23
2 of 5
33

No. Both will result in the internal ToNumber(string) function being called.

From ES5 section 15.7.1 (The Number Constructor Called as a Function):

When Number is called as a function rather than as a constructor, it performs a type conversion...

Returns a Number value (not a Number object) computed by ToNumber(value) if value was supplied, else returns +0.

From ES5 section 15.1.2.3 (parseFloat (string)):

... If neither trimmedString nor any prefix of trimmedString satisfies the syntax of a StrDecimalLiteral (see 9.3.1) ...

And 9.3.1 is the section titled "ToNumber Applied to the String Type", which is what the first quote is referring to when it says ToNumber(value).


Update (see comments)

By calling the Number constructor with the new operator, you will get an instance of the Number object, rather than a numeric literal. For example:

typeof new Number(10); //object
typeof Number(10); //number

This is defined in section 15.7.2 (The Number Constructor):

When Number is called as part of a new expression it is a constructor: it initialises the newly created object.

🌐
GitHub
github.com › lodash › lodash › issues › 3326
_.toNumber('') returns 0 not NaN · Issue #3326 · lodash/lodash
May 19, 2017 - Because parseInt('') pr parseFloat('') in JS return NaN. The same as ' '. But in Lodash _.toNumber('') or _.toNumber(' ') returns 0.
Author   wangzi6147
🌐
GeeksforGeeks
geeksforgeeks.org › javascript › lodash-_-isfloat-method
Lodash _.isFloat() Method - GeeksforGeeks
September 29, 2020 - // Defining lodash contrib variable var _ = require('lodash-contrib'); // Checking console.log("The Value is Float : " + _.isFloat(5.56)); console.log("The Value is Float : " + _.isFloat(5.0)); console.log("The Value is Float : " + _.isFloat(5)); console.log("The Value is Float : " + _.isFloat(0.5));
🌐
Dustin John Pfister
dustinpfister.github.io › 2018 › 08 › 03 › lodash_round
The lodash _.round method compared to Math.round, and formating fun. | Dustin John Pfister at github pages
January 23, 2022 - There is also the toFixed method of the number prototype that will return a string form of a number to a given number of fixed decimal points. This string result can then be feed back to a method like parseFloat to convert it back to a number again.