0

I am getting NaN as result and its beacuse my jquery is multiplying numbers that look like "204,3 * 3"

How can I deal with it?

I cant change the price, so what can I do?

"234 * 2" works fine as soon as the number have ',' I get NaN.

<script type="text/javascript">
    $('.quantity').keyup(function () {
        var parent = $(this).parent(),
            price = parent.find('.price').html(),
            quantity = parent.find('.quantity').val(),
            result = price * quantity;
        parent.find('.price2').html(result);
    });
</script>

     <span class="price">69,9</span>
     <input type="text" class="quantity">    
     <span class="price2">69,9</span>
     <span class="total">Total:</span>
     <div class="line2"></div>

Check my JSfiddle everything is there

Any kind of help is appreciated

bfavaretto
  • 70,503
  • 15
  • 107
  • 148
Aliana Rose
  • 53
  • 1
  • 7
  • 1
    Feel free to post the code here. Questions should be self-contained, we don't want to rely on outside websites being available forever to keep questions on SO useful. – Collin Nov 01 '12 at 02:22
  • 2
    Use `204.3` instead. Also, it is generally best to convert stuff to floats, if that is how you intend to use them. – Brad Nov 01 '12 at 02:23
  • Javascript has trouble with commas. See this question: http://stackoverflow.com/questions/3205730/javascript-parsefloat-500-000-returns-500-when-i-need-500000 – Laurence Nov 01 '12 at 02:24

3 Answers3

4

Javascript uses North American number formatting, which means the , is used as a thousands seperator and the . is used decimal separator.

You have two solutions to your problem:

  • Teach your users to enter numbers like 1000.25
  • Write a routine to turn 1.000,25 into 1000.25

String.prototype.replace would be your friend on the second choice.

Jeremy J Starcher
  • 22,523
  • 6
  • 52
  • 73
1

You're trying to multiply strings...use the parseFloat() and a replace() method as shown in your jsFiddle update here

 $('.quantity').keyup(function () {
    var parent = $(this).parent(),
        price = parent.find('.price').html().replace(',', '.'),
        quantity = parent.find('.quantity').val().replace(',','.'),
        result = parseFloat(price) * parseFloat(quantity);
    parent.find('.price2').html(result);
});
Pastor Bones
  • 6,895
  • 3
  • 34
  • 56
1

You are multiplying two strings here and not numbers..

Convert them using parseInt with radix

OR

Convert them using parseFloat

Change this line

 result = price * quantity;

TO

result = parseInt(price,10) * parseInt(quantity,10);

OR

result = parseFloat(price) * parseFloat(quantity);
Sushanth --
  • 54,565
  • 8
  • 62
  • 98