1

I have an issue with the JavaScript validation.

In the if condition I am checking few textbox values which will be decimal always but the if condition returns true for the following! (I checked with the numbers in chrome console).

76.02 != 61.02 + 15

However it returns false for the following.

76.02 != 61 + 15.02

When I checked 61.02+15 it returns 76.02000000000001 and 61+15.02 = 76.02.

Can anyone tell me why?

And how to fix the issues like this?

Code

if (getNumber($(this).find('[id$="txtAllowed"]').val()) !=
    (getNumber($(this).find('[id$="txtPayment"]').val())
    + getNumber($(this).find('[id$="txtBal"]').val()))
{
}

function getNumber(val) {
    if (val.trim() == "") {
        return 0;
    } else if (isNaN(val.trim())) {
        return 0;
    }
    return parseFloat(val.trim());
}

Thank You.

Bharadwaj
  • 2,535
  • 1
  • 22
  • 35

2 Answers2

1

Try to use round() or in yor case .toFixed()

(12121.3243434).toFixed(2)

The toFixed() method converts a number into a string, keeping a specified number of decimals.

Vasiliy vvscode Vanchuk
  • 7,007
  • 2
  • 21
  • 44
1

Numbers in Javascript can only represent quantities that are of the form

n / (2**k)

where both n and k are integers. In addition to this there are also limits on how big k and n can be.

In other words for fractional numbers the only quantities that can be represented exactly have a denominator that is an integral power of two in a certain range.

The numer 1/10 = 0.1 and its multiples are not represented exactly in Javascript (you can think to them as the equivalent of 1/3 = 0.3333333... in base 10: no power of two will give you an integral number when multiplied by 0.1) and this is the source of the problems you are observing.

For this reason any code that uses equal/not-equal comparisons between floating point numbers is at least suspect. When you are using approximate quantities even a+b+c is not necessarily equal to c+b+a because the internal necessary approximations will happen in a different sequence.

6502
  • 112,025
  • 15
  • 165
  • 265