-4

Why my javascript Comparison Operators code working incorrect ?

On this code requests_withdraw is 300 and money is

1200.34 but when i tested code it's will alert not enough money for withdraw Why ? how can i do ?

<script>
reqests_withdraw = "300";
money = "1200.34";
if(reqests_withdraw > money)
{
    alert("not enough money for withdraw");
}
else
{
	alert("OK");
}
</script>

3
  • 10
    You're comparing strings, not numbers. Commented Aug 17, 2017 at 13:50
  • 1
    btw, it is working correctly. Commented Aug 17, 2017 at 13:51
  • I'm sure there's a dupe for this... Can't find one though. Commented Aug 17, 2017 at 13:51

4 Answers 4

2

You are comparing string not numbers

Remove the double quotes

reqests_withdraw = 300;
money = 1200.34;
if (reqests_withdraw > money) {
  alert("not enough money for withdraw");
} else {
  alert("OK");
}

Sign up to request clarification or add additional context in comments.

Comments

2

you are comparing strings in your code, you need to use parseFloat()

<script>
reqests_withdraw = "300";
money = "1200.34";
if(parseFloat(reqests_withdraw) > parseFloat(money))
{
    alert("not enough money for withdraw");
}
else
{
	alert("OK");
}
</script>

3 Comments

This is good if he is going to collect input from the html in a textarea but if not Weedoze's answer is better. There's no need to parse a string into a number when you can start with a number.
that would be the probable case I suppose, why would anyone initialize numbers as strings in quotes
ya the only reason to do that would be as a placeholder to make sure the javascript is all valid before integrating it with html. I vote its a beginner's error though
1

Above have already been answered, but as an option, another way to turn a string into a number

    reqests_withdraw = "300";
    money = "1200.34";
    if(+reqests_withdraw > +money)
    {
        alert("not enough money for withdraw");
    }
    else
    {
        alert("OK");
    }

1 Comment

Upvote because i didn't know that
0

Yo have string there and it compares first letter. if there are equal it compare second letter.

"330.23">"340"
false
"330.23">"240"
true
"330.23">"2040"
true

to use them in if statement convert values to float using parseFloat

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.