0
received = parseFloat($('input[name=amount_received]').val()).toFixed(2);
total_amount= parseFloat($('input[name=total_bill]').val()).toFixed(2);

wherein the inputted value for received is 99 and 3930.85 for total amount

if(received >= total_amount) {

console.log("full");

} else {

console.log("partial");

}

it always says full,

can someone please help and explain why

Charlie Martin
  • 8,208
  • 3
  • 35
  • 41
MadHatter
  • 3
  • 2

3 Answers3

0

Because toFixed() returns a string, you're comparing strings instead of numbers. In a string-based comparison, 99 will come after 3930.85, and the greater-than-or-equal comparison will evaluate to true.

Getting rid of the call to toFixed() will solve it.

received = parseFloat($('input[name=amount_received]').val());
total_amount = parseFloat($('input[name=total_bill]').val());

if (received >= total_amount) {
  console.log("full");

} else {
  console.log("partial");
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<input name="amount_received" value="99" />
<input name="total_bill" value="3930.85" />

As a side note, using toFixed() is unreliable when it comes to rounding. In both current Chrome and Firefox, calling toFixed() yields the following inconsistent results:

35.655.toFixed(2) // Yields "36.66" (correct)
35.855.toFixed(2) // Yields "35.85" (wrong, should be "35.86")

See also the discussion here and refer to MDN for a reliable rounding method.

Community
  • 1
  • 1
Robby Cornelissen
  • 91,784
  • 22
  • 134
  • 156
-1

From the .toFixed() documentation.

Return value
A string representing the given number using fixed-point notation.

When you then do a comparison of one string >= the other its giving you a lexicologically ordered comparison (ie. "9" > "3" so "99.00" > "3930.85"). Have a look at this answer, for more details about the quirks of String based comparison.

Hold off on using .toFixed() until you've completed any arithmetic on your numbers, then use it for display.

JS

received = parseFloat($('input[name=amount_received]').val());
total_amount = parseFloat($('input[name=total_bill]').val());
Community
  • 1
  • 1
haxxxton
  • 6,422
  • 3
  • 27
  • 57
-2

When you performed the toFixed function, it converted the value to a string. Therefore, string "99" is always greater than string "3930.85".

What you could've done to fix that is:

received = parseFloat($('input[name=amount_received]').val().toFixed(2));
total_amount= parseFloat($('input[name=total_bill]').val().toFixed(2));

The code above does the conversion after the toFixed function.

Giovanni Lobitos
  • 852
  • 7
  • 19