1

There is two value 'a' and 'b'. i need to check a is greater than 'b'

if it is a big value its check the greater values. but here difference only in point values. it ignore point values

var a='20.796';
var b='20.190';
if (parseInt(a) > parseInt(b))
 {
alert("function can work");
return false;
}
3
  • Why are you defining them as Strings if you want to compare them numerically anyway? Commented Feb 21, 2013 at 22:18
  • 1
    Try using parseFloat instead Commented Feb 21, 2013 at 22:18
  • Use if (parseFloat(a) > parseFloat(b)) ... that would work fine for your particular case Commented Feb 21, 2013 at 22:20

4 Answers 4

1

You parse your numbers as integers. You want rational/real numbers instead. Use parseFloat:

var a = '20.796';
var b = '20.190';
console.log(parseInt(a,10),parseInt(b,10));
console.log(parseFloat(a),parseFloat(b));

Result:

20 20
20.769 20.190

Also, please always use the radix argument if you use parseInt(string [, radix]).

Furthermore - if a and b are numbers, don't save their values in a string. It's much easier to save their values instead:

var a = 20.796;
var b = 20.190;
Sign up to request clarification or add additional context in comments.

Comments

0

It's ignoring point values because you are parsing them as integers in the if statement conditional. You have a couple options.

  1. Define the variables as floats instead of strings; remove the parseInt function calls.
  2. Exchange the parseInt for parseFloat calls.

Comments

0

Here, your solution is to parse the strings as floating points rather than integers. For example:

var a = '20.796',
    b = '20.190';
if (parseFloat(a) > parseFloat(b)) {
    // TODO: .. code ..
}

Your code right now is parsing the strings as integers. Integers are whole number values and CANNOT contain a decimal value, meanwhile floats or floating point numbers CAN contain a decimal value. When you call 'parseInt()' on the floating point, it truncates (or removes) the decimal value and just keeps the whole value. Which is obviously not what you're looking for.

PS: I'm guessing you're new to JavaScript, and so I just want to wish you good luck with learning it. Personnaly, I find JavaScript to be a very beautiful language if you learn it well.

Comments

0

Define your numbers as numbers, and remove the call to parseInt or use parseFloat.

var a=20.796;
var b=20.190;
if (a > b)
{
    alert("function can work");
    return false;
}

or

if (parseFloat(a) > parseFloat(b))
{
    alert("function can work");
    return false;
}

2 Comments

parseFloat() does not take a second parameter; no radix is really needed.
@KarimSaNet That's what copy > paste will get ya. Lol. Indeed, parseFloat only takes one param.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.