JavaScript - Convert String/Number to a Number or Null, Return 0 for 0
Last Updated :
02 Dec, 2024
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(''));
- 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));
- 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));
- 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));
- 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));
- 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?
Method | When to Use | Why Choose It |
---|
Number() Constructor | For 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 Operator | For a concise and compact way to handle invalid or 0 values. | Clean and efficient, especially in simple validation checks. |
Similar Reads
Convert a String to Number in JavaScript To convert a string to number in JavaScript, various methods such as the Number() function, parseInt(), or parseFloat() can be used. These functions allow to convert string representations of numbers into actual numerical values, enabling arithmetic operations and comparisons.Below are the approache
4 min read
How to convert NaN to 0 using JavaScript ? NaN (Not a Number) is usually used to indicate an error condition for a function that should return a valid number but it can be converted to 0 using JavaScript. We will discuss how to convert the NaN to 0. Below are the approaches used to convert NaN to 0 using JavaScript: Table of Content Using is
3 min read
Convert a String to an Integer in JavaScript These are the following ways to convert string to an integer in JavaScript:1. Using Number() MethodThe number() method converts a string into an integer number. It works similarly to the unary plus operator. JavaScriptlet s = "100.45"; console.log(typeof Number(s));Outputnumber 2. Using Unary + Oper
2 min read
How to convert string of any base to an integer in JavaScript ? Given a string containing an integer value and along with that user passes a base value. We need to convert that string of any base value to an integer in JavaScript. String Integer "1002" 1002 For performing the above-illustrated task, we would be using a method (or a function) provided by JavaScri
3 min read
JavaScript Number toString() Method The toString() method in JavaScript returns a number as a string. It allows converting numerical values to string representations, enabling operations like formatting output, displaying numbers in various formats, and facilitating string manipulation based on numeric values.Syntax:num.toString(base)
2 min read
How to convert a string into a integer without using parseInt() function in JavaScript ? In JavaScript, there is a simple function parseInt() to convert a string to an integer. In order to know more about the function, you can refer to this. In this article, we will learn how to convert the string to an integer without using the parseInt() function. Advantage of parseInt() over this met
3 min read