Z. Jason
Z. Jason

Reputation: 33

how to keep number input as number data type

let a = prompt ("Input value of 'a'", );
let b = prompt ("Input value of 'b'", );

alert(a);
alert(b);
alert(a + b);

Number(a);
Number(b);

if ( a + b < 4){
    result = 'Below';
} else {
    result = 'Over';
}

alert (result);

So I was doing some kinda javascript practice and I encountered some issues with the above.

The output, take for e.g. a = 1, b = 2, instead of a + b = 3, the result is a + b = 12.

I thought that javascript auto recognise number as number data type, especially with the use of mathematics operators.

i tried:

let a = prompt ("Input value of 'a'", Number());

to specifically turn the input value into number data type but the problem still exist and it's puzzling me.

thank in advance for any helps given!!

Upvotes: 2

Views: 379

Answers (2)

maha
maha

Reputation: 643

The function Number() works right, but your problem is that you didn't reassign the value to the variable.

You need to assign it like this : a = Number(a). This is how should be your code:

let a = prompt ("Input value of 'a'");
let b = prompt ("Input value of 'b'");

console.log("Before Number");
console.log("a: "+a+"   b: "+b+ "    a + b: "+(a + b));

a = Number(a);
b = Number(b);

let result = '';

if ( a + b < 4){
    result = 'Below';
} else {
    result = 'Over';
}

console.log("After Number");
console.log("a: "+a+"   b: "+b+ "    a + b: "+(a + b));

console.log(result);

Upvotes: 1

Vikasdeep Singh
Vikasdeep Singh

Reputation: 21756

You are getting a and b as string so a+b is appending to string.

First you need to convert that to number and then perform + operation.

    let a = prompt ("Input value of 'a'", );
    let b = prompt ("Input value of 'b'", );

    a = Number(a);
    b = Number(b);

    alert(a);
    alert(b);
    alert(a + b);

    if ( a + b < 4){
        result = 'Below';
    } else {
        result = 'Over';
    }

   alert (result);

Working Demo is here:

let a = "1" // value from prompt
let b = "2" // value from prompt

a = Number(a);
b = Number(b);

console.log(a);
console.log(b);
console.log(a + b);

if (a + b < 4) {
  result = 'Below';
} else {
  result = 'Over';
}

console.log(result);

It will work.

Note:

Instead of using multiple alerts its better to show/test values using console.log() which is a good practice.

Upvotes: 0

Related Questions