"If a worker wants to do his job well, he must first sharpen his tools." - Confucius, "The Analects of Confucius. Lu Linggong"
Front page > Programming > How Can I Perform Math on Strings in JavaScript?

How Can I Perform Math on Strings in JavaScript?

Published on 2024-12-21
Browse:145

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
Latest tutorial More>

Disclaimer: All resources provided are partly from the Internet. If there is any infringement of your copyright or other rights and interests, please explain the detailed reasons and provide proof of copyright or rights and interests and then send it to the email: [email protected] We will handle it for you as soon as possible.

Copyright© 2022 湘ICP备2022001581号-3