Number conversion in JavaScript can be performed in several ways:
+value
value * 1
, value - 0
Method | Syntax | Features | Example |
---|---|---|---|
Number() | Number(value) | Strict conversion | Number("123") → 123 |
parseInt() | parseInt(value, radix) | Integer parsing | parseInt("123px") → 123 |
parseFloat() | parseFloat(value) | Float parsing | parseFloat("3.14px") → 3.14 |
Unary plus | +value | Short notation | +"123" → 123 |
Mathematical operations | value * 1 | Implicit conversion | "123" * 1 → 123 |
// Strings with numbers
console.log(Number("123")); // 123
console.log(Number("3.14")); // 3.14
console.log(Number("-42")); // -42
console.log(Number("0")); // 0
// Boolean values
console.log(Number(true)); // 1
console.log(Number(false)); // 0
// null and undefined
console.log(Number(null)); // 0
console.log(Number(undefined)); // NaN
// Empty strings and whitespace
console.log(Number("")); // 0
console.log(Number(" ")); // 0
console.log(Number("\n\t")); // 0
// Strict conversion - any extra character gives NaN
console.log(Number("123px")); // NaN
console.log(Number("12.34.56")); // NaN
console.log(Number("abc")); // NaN
console.log(Number("123 456")); // NaN
// But works with scientific notation
console.log(Number("1e3")); // 1000
console.log(Number("2.5e-2")); // 0.025
console.log(Number("Infinity")); // Infinity
console.log(Number("-Infinity")); // -Infinity
// Safety with different types
let values = ["123", true, null, undefined, "", " "];
values.forEach(val => {
console.log(`${val} → ${Number(val)}`);
});
// Valid number check
function isValidNumber(value) {
return !isNaN(Number(value)) && Number(value) !== Infinity;
}
console.log(isValidNumber("123")); // true
console.log(isValidNumber("abc")); // false
console.log(isValidNumber("")); // true (0)
// Basic usage
console.log(parseInt("123")); // 123
console.log(parseInt("123.45")); // 123 (discards fractional part)
console.log(parseInt("123px")); // 123 (ignores non-numeric characters)
console.log(parseInt("px123")); // NaN (must start with number)
// With whitespace
console.log(parseInt(" 123 ")); // 123
console.log(parseInt("\n\t123\r")); // 123
// Negative numbers
console.log(parseInt("-123")); // -123
console.log(parseInt("+123")); // 123
// Different number systems
console.log(parseInt("1010", 2)); // 10 (binary)
console.log(parseInt("777", 8)); // 511 (octal)
console.log(parseInt("ff", 16)); // 255 (hexadecimal)
console.log(parseInt("zz", 36)); // 1295 (maximum base)
// Auto-detection of base (not recommended)
console.log(parseInt("0x10")); // 16 (hex)
console.log(parseInt("010")); // 10 (not octal in modern JS)
// Practical example
function hexToDecimal(hex) {
return parseInt(hex.replace('#', ''), 16);
}
console.log(hexToDecimal('#ff0000')); // 16711680
// Stops at first non-numeric character
console.log(parseInt("123abc456")); // 123
console.log(parseInt("12.34.56")); // 12
console.log(parseInt("1e3")); // 1 (doesn't understand scientific notation)
// Problems with floating numbers as strings
console.log(parseInt(0.0000008)); // 8 (converts to "8e-7")
console.log(parseInt(0.000008)); // 8
console.log(parseInt(999999999999999999999)); // 1 (large numbers)
// Safe usage
function safeParseInt(value, radix = 10) {
if (typeof value === 'number') {
return Math.floor(value);
}
return parseInt(String(value), radix);
}
// Basic usage
console.log(parseFloat("3.14")); // 3.14
console.log(parseFloat("3.14159px")); // 3.14159
console.log(parseFloat("123")); // 123
console.log(parseFloat("123.")); // 123
// With whitespace
console.log(parseFloat(" 3.14 ")); // 3.14
console.log(parseFloat("\n3.14\t")); // 3.14
// Scientific notation
console.log(parseFloat("1.23e-4")); // 0.000123
console.log(parseFloat("1.23E+2")); // 123
// Stops at second decimal separator
console.log(parseFloat("3.14.159")); // 3.14
console.log(parseFloat("3,14")); // 3 (doesn't understand comma)
// Infinity
console.log(parseFloat("Infinity")); // Infinity
console.log(parseFloat("-Infinity")); // -Infinity
// Errors
console.log(parseFloat("abc")); // NaN
console.log(parseFloat("")); // NaN
// Practical application
function parsePrice(priceString) {
// "$123.45" → 123.45
const cleaned = priceString.replace(/[^\d.-]/g, '');
return parseFloat(cleaned) || 0;
}
console.log(parsePrice("$123.45")); // 123.45
console.log(parsePrice("€1,234.56")); // 1234.56
// Simple cases
console.log(+"123"); // 123
console.log(+"3.14"); // 3.14
console.log(+"-42"); // -42
console.log(+true); // 1
console.log(+false); // 0
console.log(+null); // 0
console.log(+undefined); // NaN
// Equivalent to Number()
console.log(+"123" === Number("123")); // true
console.log(+"abc" === Number("abc")); // true (both NaN)
// In conditions
let userInput = "25";
if (+userInput > 18) {
console.log("Adult");
}
// In arrays
let stringNumbers = ["1", "2", "3", "4", "5"];
let numbers = stringNumbers.map(str => +str);
console.log(numbers); // [1, 2, 3, 4, 5]
// With dates
let timestamp = +new Date(); // current time in milliseconds
console.log(timestamp);
// Quick number check
function isNumeric(value) {
return !isNaN(+value) && isFinite(+value);
}
console.log(isNumeric("123")); // true
console.log(isNumeric("abc")); // false
// Multiplication by 1
console.log("123" * 1); // 123
console.log("3.14" * 1); // 3.14
console.log(true * 1); // 1
console.log(false * 1); // 0
// Subtraction of zero
console.log("123" - 0); // 123
console.log("3.14" - 0); // 3.14
// Division by 1
console.log("123" / 1); // 123
console.log("3.14" / 1); // 3.14
// Double negation with mathematical operation
console.log(~~"123.45"); // 123 (conversion to integer)
// Operator precedence
console.log("5" + 3); // "53" (concatenation)
console.log("5" - 3); // 2 (subtraction)
console.log("5" * 3); // 15 (multiplication)
console.log("5" / 3); // 1.6666666666666667 (division)
// With multiple operands
console.log("10" - "5" + "2"); // "52" (10-5=5, then 5+"2"="52")
console.log("10" - "5" - "2"); // 3 (all subtraction operations)
// Practical application
function calculateTotal(prices) {
return prices.reduce((sum, price) => sum + (price * 1), 0);
}
let prices = ["10.50", "25.00", "5.75"];
console.log(calculateTotal(prices)); // 41.25
Criteria | Number() | parseInt() | parseFloat() | Unary + | Math operations |
---|---|---|---|---|---|
Strictness | High | Low | Low | High | High |
Floating numbers | ✅ | ❌ | ✅ | ✅ | ✅ |
String parsing | Strict | Flexible | Flexible | Strict | Strict |
Number systems | ❌ | ✅ | ❌ | ❌ | ❌ |
Performance | Medium | High | High | High | High |
Code readability | Excellent | Good | Good | Medium | Low |
console.log(Number(""));
console.log(Number(" "));
console.log(Number("0"));
console.log(Number("00"));
console.log(Number("123abc"));
0
, 0
, 0
, 0
, NaN
Number() strictly converts values. Empty strings and whitespace give 0, any non-numeric characters give NaN.
function getAge(input) {
return Number(input);
}
console.log(getAge("25")); // 25 - works
console.log(getAge("25 years")); // NaN - doesn't work!
function getAge(input) {
return parseInt(input, 10); // or
// return parseFloat(input);
}
// Or more reliable version
function getAge(input) {
const num = parseInt(input, 10);
return isNaN(num) ? 0 : num;
}
Use parseInt() to extract number from string with text.
// Need to extract numeric value from strings like "$123.45", "€67.89"
function extractAmount(priceString) {
// Your code here
}
console.log(extractAmount("$123.45")); // should be 123.45
console.log(extractAmount("€67.89")); // should be 67.89
function extractAmount(priceString) {
// Remove all characters except digits, dot and minus
const cleaned = priceString.replace(/[^\d.-]/g, '');
return parseFloat(cleaned) || 0;
}
// Alternative with regular expression
function extractAmount(priceString) {
const match = priceString.match(/[+-]?\d+(\.\d+)?/);
return match ? parseFloat(match[0]) : 0;
}
// Create a function that checks if string is a valid number
function isValidNumber(input) {
// Your code here
}
console.log(isValidNumber("123")); // true
console.log(isValidNumber("123.45")); // true
console.log(isValidNumber("abc")); // false
console.log(isValidNumber("")); // false
console.log(isValidNumber("Infinity")); // false
function isValidNumber(input) {
const num = Number(input);
return !isNaN(num) && isFinite(num) && input.trim() !== '';
}
// Stricter version
function isValidNumber(input) {
return /^[+-]?\d+(\.\d+)?$/.test(input.trim());
}
// With scientific notation support
function isValidNumber(input) {
return /^[+-]?\d+(\.\d+)?([eE][+-]?\d+)?$/.test(input.trim());
}
// Which method is faster for string array?
let stringNumbers = ["1", "2", "3", "4", "5"];
// Option A
let resultA = stringNumbers.map(str => Number(str));
// Option B
let resultB = stringNumbers.map(str => +str);
// Option C
let resultC = stringNumbers.map(str => parseInt(str, 10));
// Option D
let resultD = stringNumbers.map(str => str * 1);
Option B (unary plus) is usually fastest. Option D (multiplication by 1) is also fast. Option A (Number()) is more readable. Option C (parseInt()) is redundant for simple numbers.
// Optimal solution
let result = stringNumbers.map(str => +str);
class SafeNumber {
static convert(value, defaultValue = 0) {
if (value === null || value === undefined) {
return defaultValue;
}
const num = Number(value);
if (isNaN(num) || !isFinite(num)) {
return defaultValue;
}
return num;
}
static parseInt(value, radix = 10, defaultValue = 0) {
const num = parseInt(value, radix);
return isNaN(num) ? defaultValue : num;
}
static parseFloat(value, defaultValue = 0) {
const num = parseFloat(value);
return isNaN(num) ? defaultValue : num;
}
}
// Usage
console.log(SafeNumber.convert("123")); // 123
console.log(SafeNumber.convert("abc")); // 0
console.log(SafeNumber.convert("abc", -1)); // -1
// Benchmark different methods
function benchmark() {
const iterations = 1000000;
const value = "12345";
console.time('Number()');
for (let i = 0; i < iterations; i++) {
Number(value);
}
console.timeEnd('Number()');
console.time('parseInt()');
for (let i = 0; i < iterations; i++) {
parseInt(value, 10);
}
console.timeEnd('parseInt()');
console.time('parseFloat()');
for (let i = 0; i < iterations; i++) {
parseFloat(value);
}
console.timeEnd('parseFloat()');
console.time('Unary +');
for (let i = 0; i < iterations; i++) {
+value;
}
console.timeEnd('Unary +');
console.time('Math operation');
for (let i = 0; i < iterations; i++) {
value * 1;
}
console.timeEnd('Math operation');
}
// benchmark(); // Uncomment for testing
// BigInt for very large numbers
function convertToBigInt(value) {
try {
return BigInt(value);
} catch (e) {
console.log('BigInt conversion error:', e.message);
return 0n;
}
}
console.log(convertToBigInt("123456789012345678901234567890"));
// Safe integer check
function safeInteger(value) {
const num = Number(value);
if (!Number.isSafeInteger(num)) {
console.warn(`Number ${value} may lose precision`);
return convertToBigInt(value);
}
return num;
}
console.log(safeInteger("9007199254740991")); // safe
console.log(safeInteger("9007199254740992")); // warning
// Parsing numbers with locale consideration
function parseLocalizedNumber(value, locale = 'en-US') {
// Remove thousand separators and replace decimal separator
if (locale === 'ru-RU') {
// "1 234,56" → "1234.56"
const normalized = value
.replace(/\s/g, '') // remove spaces
.replace(',', '.'); // replace comma with dot
return parseFloat(normalized);
}
if (locale === 'en-US') {
// "1,234.56" → "1234.56"
const normalized = value.replace(/,/g, '');
return parseFloat(normalized);
}
return parseFloat(value);
}
console.log(parseLocalizedNumber("1 234,56", 'ru-RU')); // 1234.56
console.log(parseLocalizedNumber("1,234.56", 'en-US')); // 1234.56
// Using Intl.NumberFormat for parsing
function parseWithIntl(value, locale = 'en-US') {
const formatter = new Intl.NumberFormat(locale);
const parts = formatter.formatToParts(1234.56);
let decimalSeparator = '.';
let groupSeparator = ',';
parts.forEach(part => {
if (part.type === 'decimal') decimalSeparator = part.value;
if (part.type === 'group') groupSeparator = part.value;
});
const normalized = value
.split(groupSeparator).join('')
.replace(decimalSeparator, '.');
return parseFloat(normalized);
}
// Dangerous - parseInt() can give unexpected results
console.log(parseInt("08")); // 8 (good)
console.log(parseInt("08", 10)); // 8 (better)
console.log(parseInt(0.0000008)); // 8 (bad! converts to "8e-7")
// Safe
console.log(Number("08")); // 8
console.log(Number(0.0000008)); // 8e-7
// Correct approach
function safeParseInt(value) {
if (typeof value === 'number') {
return Math.floor(value);
}
return parseInt(String(value), 10);
}
// Precision problem
console.log(0.1 + 0.2); // 0.30000000000000004
console.log(parseFloat("0.1") + parseFloat("0.2")); // 0.30000000000000004
// Solution
function addFloats(a, b, precision = 10) {
return parseFloat((parseFloat(a) + parseFloat(b)).toFixed(precision));
}
console.log(addFloats("0.1", "0.2")); // 0.3
// Or use libraries like decimal.js
// Different behavior with empty values
console.log(Number("")); // 0
console.log(Number(" ")); // 0
console.log(parseInt("")); // NaN
console.log(parseFloat("")); // NaN
console.log(+""); // 0
// Safe check
function convertToNumber(value) {
if (value === null || value === undefined || value === '') {
return null; // or other default value
}
const num = Number(value);
return isNaN(num) ? null : num;
}
// Unexpected results
console.log("5" + 3); // "53" (concatenation)
console.log("5" - 3); // 2 (subtraction)
console.log("5" * "3"); // 15 (multiplication)
console.log("5" / "3"); // 1.6666666666666667 (division)
// Explicit conversion for predictability
function calculate(a, b, operation) {
const numA = Number(a);
const numB = Number(b);
if (isNaN(numA) || isNaN(numB)) {
throw new Error('Invalid numeric values');
}
switch (operation) {
case '+': return numA + numB;
case '-': return numA - numB;
case '*': return numA * numB;
case '/': return numA / numB;
default: throw new Error('Unknown operation');
}
}
// Integer check
console.log(Number.isInteger(123)); // true
console.log(Number.isInteger(123.0)); // true
console.log(Number.isInteger(123.45)); // false
console.log(Number.isInteger("123")); // false (string!)
// Safe integer check
console.log(Number.isSafeInteger(123)); // true
console.log(Number.isSafeInteger(Math.pow(2, 53) - 1)); // true
console.log(Number.isSafeInteger(Math.pow(2, 53))); // false
// Practical application
function validateInteger(value) {
const num = Number(value);
if (!Number.isInteger(num)) {
throw new Error('Value must be an integer');
}
if (!Number.isSafeInteger(num)) {
console.warn('Number may lose precision');
}
return num;
}
// Number object methods (ES6+)
console.log(Number.parseInt === parseInt); // true
console.log(Number.parseFloat === parseFloat); // true
// Advantage - no global pollution
const myParseInt = Number.parseInt;
const myParseFloat = Number.parseFloat;
// Functional style usage
const stringNumbers = ["1", "2.5", "3.14", "4"];
const integers = stringNumbers.map(Number.parseInt);
const floats = stringNumbers.map(Number.parseFloat);
console.log(integers); // [1, 2, 3, 4]
console.log(floats); // [1, 2.5, 3.14, 4]
// Working with very large numbers
const bigNumber = BigInt("123456789012345678901234567890");
console.log(bigNumber); // 123456789012345678901234567890n
// Converting strings to BigInt
function stringToBigInt(str) {
try {
return BigInt(str);
} catch (e) {
console.error('BigInt conversion error:', e.message);
return null;
}
}
// BigInt cannot be mixed with regular numbers
try {
console.log(bigNumber + 1); // TypeError
} catch (e) {
console.log('Error:', e.message);
}
// Correct way
console.log(bigNumber + 1n); // 123456789012345678901234567891n
Number conversion in JavaScript is an important operation with many nuances. It’s important to understand:
✅ Number() — strict and safe conversion
✅ parseInt() — for extracting integers from strings
✅ parseFloat() — for extracting floating-point numbers
✅ Unary plus — short and fast method
✅ Validation — always check result for NaN and Infinity
In modern development, prefer:
Number()
for strict conversionparseInt(value, 10)
for extracting integersparseFloat()
for parsing floating-point numbersisNaN()
and isFinite()
BigInt
for working with very large numbersMaster these methods to confidently handle number conversions in any JavaScript project! 🚀