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
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