-3

I have this small piece of code to check if a variable is a number or not, but does not work

var cost_value= 7777;
alert(cost_value);
if (typeof(cost_value) !== "number") {
    alert("not a number");//7777
 } else {
   alert("a number");
 }

But it will always alert as a "not a number"

change to if(jQuery.type(cost_value) !== "number"

Does not work, any ideas?

Danielle Rose Mabunga
  • 1,676
  • 4
  • 25
  • 48
  • 4
    Cannot reproduce. If anything, rubberduck-debug your code next time and provide a [Minimal, Complete, and ***Verifiable*** example](http://stackoverflow.com/help/mcve). This is far too easy, so you should be able to figure this out on your own. – Sebastian Simon Aug 26 '16 at 06:10
  • why do you need a solution given by Jquery when you have a stable JS solution? JQUERY is JAVASCRIPT – Rajaprabhu Aravindasamy Aug 26 '16 at 06:11
  • In your real code you're getting `cost_value` from a HTML element content or value? – Teemu Aug 26 '16 at 06:11
  • 2
    Cannot be reproduced, because the author hat typeOf(costvalue) first. After a few seconds he/she editted his/her code. – Tobias S Aug 26 '16 at 06:11
  • You can try alert(typeof(cost_value)). – mm759 Aug 26 '16 at 06:12
  • Reasons like this are why TypeScript makes things much easier. – ryanlutgen Aug 26 '16 at 06:13
  • 2
    Run your edited code. It alerts "a number". You are probably getting your variable assigned by some other input, as @Teemu described. – Larkeith Aug 26 '16 at 06:14
  • Possible duplicate of [Check whether variable is number or string in javascript](http://stackoverflow.com/questions/1303646/check-whether-variable-is-number-or-string-in-javascript) – Irfan Anwar Aug 26 '16 at 06:22
  • @MuhammadIrfan This is actually less helpful in this scenario. The appropriate action is to flag this question as off-topic (no-repro/typo). – Sebastian Simon Aug 26 '16 at 06:23

2 Answers2

-1

With jQuery you could use isNumeric

var cost_value = 7777;
if (!$.isNumeric(cost_value)) {
    alert("not a number");//7777
 } else {
   alert("a number");
 }
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

Edit: I've seen the first comment and your spelling error, so this problem is already fixed.

Tobias S
  • 1,275
  • 8
  • 23
-1

You can do something like that

var cost_value= 7777;
console.log(typeof(cost_value));
if (String(typeof(cost_value)) !== "number") {
    alert("not a number");//7777
 } else {
   alert("a number");
 }

https://jsfiddle.net/Refatrafi/42m3b8u0/3/

Rafi Ud Daula Refat
  • 2,187
  • 19
  • 28
  • I don’t see how this is helpful in any way. – Sebastian Simon Aug 26 '16 at 06:16
  • 1
    No, the current code in the question already unexpectedly “works”. This answer just adds confusing fluff to the code without explanation. Anyway, no answers should even be added to this question because it’s based on a typo and therefore off-topic. – Sebastian Simon Aug 26 '16 at 06:18