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

Actually am trying the following one like..<!DOCTYPE html><html><body><p>A n

Actually am trying the following one like..

<!DOCTYPE html>
<html>
<body>
<p>A number divided by a non-numeric string bees 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 bees NaN (Not a Number):

10

Please explain me why its ing like this.

Thanks..

Actually am trying the following one like..

<!DOCTYPE html>
<html>
<body>
<p>A number divided by a non-numeric string bees 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 bees NaN (Not a Number):

10

Please explain me why its ing like this.

Thanks..

Share Improve this question asked Oct 9, 2014 at 12:04 Ramesh_KondaRamesh_Konda 1113 silver badges12 bronze badges 6
  • "10" is not a non-numeric string, "AA" would be a non-numeric string. – Michael Commented Oct 9, 2014 at 12:06
  • What do you want to see in output? – Serkan Commented Oct 9, 2014 at 12:08
  • then output has to e NaN. But its giving 10. Thats my problem? @MiChael – Ramesh_Konda Commented Oct 9, 2014 at 12:10
  • No, it should not e NaN. "10" IS a numeric string. – Utopik Commented Oct 9, 2014 at 12:11
  • am expecting output as NaN. beacause typeof "10" is string @serkan – Ramesh_Konda Commented Oct 9, 2014 at 12:12
 |  Show 1 more ment

3 Answers 3

Reset to default 4

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"

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

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

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') {
    // ...
}

发布者:admin,转转请注明出处:http://www.yc00.com/questions/1745144640a4613591.html

相关推荐

发表回复

评论列表(0条)

  • 暂无评论

联系我们

400-800-8888

在线咨询: QQ交谈

邮件:admin@example.com

工作时间:周一至周五,9:30-18:30,节假日休息

关注微信