Ramesh_Konda
Ramesh_Konda

Reputation: 111

Is it possible to divide a number with string in javascript?

Actually am trying the following one like..

<!DOCTYPE html>
<html>
<body>
<p>A number divided by a non-numeric string becomes NaN (Not a Number):</p>

<p id="demo"></p>

<script>
var d = "10";  //typeof d is string
document.getElementById("demo").innerHTML = 100/d; 
// or document.getElementById("demo").innerHTML = 100/"10";
</script>

</body>
</html>

OUTPUT its giving me like..

A number divided by a non-numeric string becomes NaN (Not a Number):

10

Please explain me why its coming like this.

Thanks..

Upvotes: 1

Views: 4573

Answers (3)

Niranjan Borawake
Niranjan Borawake

Reputation: 1638

If one of the operands is a string, JavaScript will try to convert it to a number first (ie: "5" becomes 5), or if unsuccessful, NaN is returned for the expression.

This is the reason why 100/"10" gives 10 and not NaN.

Upvotes: 2

Aesthete
Aesthete

Reputation: 18848

Unary operators will attempt to convert the string to a number. It will only produce NaN if the string cannot by converted to a number.

You'll notice the same if you try the following, which will convert from hex to 10:

100/"0xA"

Upvotes: 4

epoch
epoch

Reputation: 16605

add + to convert the variable to a number:

var d = "10";  //typeof d is string
document.getElementById("demo").innerHTML = 100 / +d;
// -----------------------------------------------^-- 

And for the opposite, you can do a typeof check:

if (typeof d !== 'number') {
    // ...
}

Upvotes: 0

Related Questions