Open In App

JavaScript - Convert String/Number to a Number or Null, Return 0 for 0

Last Updated : 02 Dec, 2024
Comments
Improve
Suggest changes
Like Article
Like
Report

In JavaScript, you may need to convert a string or a number into a valid number, while handling special cases like returning null for invalid inputs or 0 for input values of 0. Here are the different approaches to convert string/number to a number or null, return 0 for 0.

1. Using Number() Constructor

The Number() function is a built-in JavaScript method that converts a string or number to a number. If the conversion is not possible, it returns NaN (Not a Number). We can then add a check to return null for invalid values and handle the special case for 0.

JavaScript
function convertNum(value) {
    let n = Number(value);
    return isNaN(n) ? null : n === 0 ? 0 : n;
}

console.log(convertNum('123'));
console.log(convertNum('abc'));
console.log(convertNum('0'));
console.log(convertNum(0));
console.log(convertNum('')); 

Output
123
null
0
0
0
  • Number(value) converts the input to a number. If it cannot be converted, it returns NaN.
  • isNaN(num) checks if the conversion resulted in NaN. If true, it returns null.
  • The special case for 0 ensures that 0 is explicitly returned when the input is either '0' or 0 itself.

2. Using parseInt() or parseFloat()

If you want to convert a string to a whole number (parseInt()) or a floating-point number (parseFloat()), both methods behave similarly to Number() but also parse the string from the beginning until they encounter a character that is not a valid digit.

JavaScript
function convertInt(value) {
    let n = parseInt(value, 10);
    return isNaN(n) ? null : n === 0 ? 0 : n;
}

console.log(convertInt('123abc'));
console.log(convertInt('abc')); 
console.log(convertInt('0')); 
console.log(convertInt(0));   

Output
123
null
0
0
  • parseInt(value, 10) converts a string to an integer (ignoring any characters after the first valid number).
  • parseFloat(value) would convert to a floating-point number, handling decimal values.
  • The same check for isNaN(num) ensures that invalid conversions return null.

3. Using Unary Plus (+) Operator

The unary plus (+) operator is a shorthand for converting a value to a number. It works similarly to Number(), but it is often faster and more concise.

JavaScript
function convertUnary(value) {
    let n = +value;
    return isNaN(n) ? null : n === 0 ? 0 : n;
}

console.log(convertUnary('456'));
console.log(convertUnary('hello'));
console.log(convertUnary('0'));
console.log(convertUnary(0)); 

Output
456
null
0
0
  • The + operator attempts to convert the value to a number. It works like Number(), but is more concise.
  • As with the other methods, we check for isNaN(num) and handle the special case of 0.

4. Using Number.isNaN() for Explicit Validation

The Number.isNaN() method is a more strict version of isNaN(). While isNaN() forces the value into a number before checking, Number.isNaN() only returns true for values that are explicitly NaN. This makes it a more reliable way to check for invalid conversions.

JavaScript
function convertNaN(value) {
    let n = Number(value);
    return Number.isNaN(n) ? null : n === 0 ? 0 : n;
}

console.log(convertNaN('789'));
console.log(convertNaN('xyz'));
console.log(convertNaN('0')); 
console.log(convertNaN(0));

Output
789
null
0
0
  • Number(value) tries to convert the value to a number.
  • Number.isNaN(num) checks if the result is explicitly NaN (without coercion).
  • The logic for returning null for invalid values and 0 for valid zero is the same.

5. Using Ternary Operator for Shorter Syntax

To make the conversion and validation even more concise, you can use a ternary operator to handle the null and 0 cases in a single line.

JavaScript
function convertTernary(value) {
    let n = Number(value);
    return isNaN(n) ? null : n || 0;
}

console.log(convertTernary('123'));
console.log(convertTernary('abc')); 
console.log(convertTernary('0')); 
console.log(convertTernary(0)); 

Output
123
null
0
0
  • isNaN(num) checks for invalid conversions.
  • num || 0 uses the fact that 0 is falsy in JavaScript. If the number is 0, it returns 0; otherwise, it returns the valid number.

Which Approach to Choose?

MethodWhen to UseWhy Choose It
Number() ConstructorFor general conversions of string/number to a valid number.The most simple method to handle conversion with NaN checks.
parseInt() or parseFloat()When working with numbers that may include non-numeric characters.Useful when you want to parse part of a string as a number.
Unary Plus(+)For a quick and concise number conversion.Fast and concise, perfect for quick number conversions.
Number.isNaN()When you need a stricter check for NaN without type coercion.More reliable for checking invalid conversions than isNan().
Ternary OperatorFor a concise and compact way to handle invalid or 0 values.Clean and efficient, especially in simple validation checks.

Next Article

Similar Reads