Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Adding and Subtracting Numbers as Strings

I read the following on a question on SO:

'7' + 4 gives '74', whereas '7' - 4 gives 3 in JavaScript

Why does this happen?

like image 836
diEcho Avatar asked Jun 07 '10 08:06

diEcho


People also ask

What is a string of numbers?

A Number String is a set of related math problems designed to teach strategies based on number relationships. It is a 10–15 minute routine that can be used during math instruction. Prepare an area to use the number string by gathering students in an area where the whole class meets.

Can we subtract two strings?

The simplest way is to use a lib- but if you can't do that, use a string. Strings are almost infinite in length, therefore you can use them to store large "numbers". To subtract 2 numbers, you subtract each digit individually and carry over the borrows. This is the same case in programming.


2 Answers

+ is the String concatenation operator so when you do '7' + 4 you're coercing 4 into a string and appending it. There is no such ambiguity with the - operator.

If you want to be unambiguous use parseInt() or parseFloat():

parseInt('7', 10) + 4 

Why specify the radix to 10? So '077' isn't parsed as octal.

like image 121
cletus Avatar answered Sep 22 '22 03:09

cletus


The '+' operator is defined for both strings and numbers, so when you apply it to a string and a number, the number will be converted so string, then the strings will be concatenated: '7' + 4 => '7' + '4' => '74' But '-' is only defined for numbers, not strings, so the string '7' will be converted to number: '7' - 4 => 7 - 4 => 3

like image 21
Andy Avatar answered Sep 23 '22 03:09

Andy