"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 > Why Does Adding Strings Produce Concatenation, and How Can I Add Them as Numbers Instead?

Why Does Adding Strings Produce Concatenation, and How Can I Add Them as Numbers Instead?

Published on 2024-12-23
Browse:426

Why Does Adding Strings Produce Concatenation, and How Can I Add Them as Numbers Instead?

Handling Concatenation Confusion: Adding Strings as Numbers

When attempting to add strings containing numeric characters, it's common to encounter concatenation, resulting in unexpected outcomes. To resolve this issue, it's necessary to convert the strings to numerical values before performing addition.

Solution:

To force the strings to be treated as numbers, use the unary plus operator ( ). This operator converts the strings to numerical values, allowing for addition as intended:

const num1 = '20';
const num2 = '30.5';

console.log( 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