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
Release: 2025-01-04 02:40:39
Original
337 people have browsed it

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';
Copy after login

Adding these strings directly results in concatenation:

num1 + num2; // '2030.5'
Copy after login

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

+num1 + +num2;
Copy after login

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

+num1 + +num2; // 50.5
Copy after login

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!

source:php.cn
Statement of this Website
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
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template