-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>
suttakan mongkon
  • 111
  • 1
  • 2
  • 6

4 Answers4

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");
}
Weedoze
  • 13,683
  • 1
  • 33
  • 63
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>
Dij
  • 9,761
  • 4
  • 18
  • 35
  • 1
    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. – Matthew Ciaramitaro Aug 17 '17 at 13:54
  • 1
    that would be the probable case I suppose, why would anyone initialize numbers as strings in quotes – Dij Aug 17 '17 at 14:01
  • 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 – Matthew Ciaramitaro Aug 17 '17 at 14:05
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");
    }
Alex
  • 113
  • 10
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

John Tribe
  • 1,407
  • 14
  • 26