Add two values if they are numbers, and join them if they are not.
What to build
An adder that does what a person would expect, even though JavaScript's + means two different things.
Requirements
- Read two lines.
- If both are numbers, print their sum, rounded to at most 2 decimal places.
- Otherwise, print the two lines joined together, exactly as typed.
Input
Two lines of text.
Output
One line: the sum or the joined text.
Constraints
Each line is not empty and has no spaces. Numbers have at most 2 decimal places.
Example
Input:
0.1
0.2
Output:
0.3
Why it works
Testing both conversions first decides which meaning of adding you want. Rounding removes the binary error, because 0.1 + 0.2 is not exactly 0.3 in a computer.
Examples
Example 1 · Input
2 3
Expected output
5
Example 2 · Input
0.1 0.2
Expected output
0.3
Hints
Hint 1
Convert both lines first, and test each result with Number.isNaN.
Hint 2
If either one is NaN, join the original text.
Hint 3
Math.round(sum * 100) / 100 removes the tiny decimal error.
Solution
Show one correct solution (try it yourself first)
const a = prompt();
const b = prompt();
const x = Number(a);
const y = Number(b);
if (Number.isNaN(x) || Number.isNaN(y)) {
console.log(a + b);
} else {
console.log(Math.round((x + y) * 100) / 100);
}