Home >Web Front-end >JS Tutorial >How Can I Perform Math on Strings in JavaScript?

How Can I Perform Math on Strings in JavaScript?

Linda Hamilton
Linda HamiltonOriginal
2025-01-04 02:40:39323browse

How Can I Perform Math on Strings in JavaScript?

Converting Strings to Numbers for Mathematical Operations

Despite containing numerical characters, strings cannot be directly manipulated as numbers. To perform arithmetic operations, it is necessary to first convert them into numerical form.

Consider the example given:

var num1 = '20',
    num2 = '30.5';

Adding these strings directly results in concatenation:

num1 + num2; // '2030.5'

To force them to be treated as numbers, use the unary plus operator ( ):

+num1 + +num2;

The unary plus operator coerces the strings into numerical data types before performing the addition, allowing for accurate mathematical operations:

+num1 + +num2; // 50.5

The above is the detailed content of How Can I Perform Math on Strings in JavaScript?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn