0

I am trying to calculate sum of some textboxes using javascript but it gives me inaccurate results in some cases.

FIDDLE

Enter values : 234.32 and 32.34

Result: 266.65999999999997

Expected Result: 266.66

Code:

<input type="text" class="unitrate" />
<input type="text" class="unitrate" />
<input type="text" id="txtsum" />    


$(document).on('keyup', ".unitrate", function (e) {
            calculateunitrateSum();
        });


function calculateunitrateSum() {
            var unitratesum = 0;
            $(".unitrate").each(function () {
                //add only if the value is number
                if (!isNaN(this.value) && this.value.length != 0) {
                    unitratesum += parseFloat(this.value);
                }
                else {
                    $(this).val('0')
                }
            });
            $('#txtsum').val(unitratesum);
        }
SamuraiJack
  • 5,131
  • 15
  • 89
  • 195
  • 1
    http://blog.wambatech.com/javascript-gotchas-pt-1/ `:)` and http://stackoverflow.com/questions/10473994/javascript-adding-decimal-numbers-issue p.s.s I am not a downvoter, infact +1 from my end – Tats_innit Jul 08 '14 at 04:51

3 Answers3

1

You can use toFixed(2) to round it to desired number of digits.

Live Demo

 $('#txtsum').val(unitratesum.toFixed(2));

The toFixed() method formats a number using fixed-point notation.

Adil
  • 146,340
  • 25
  • 209
  • 204
0

You can round off number using:

Math.round(unitratesum * 100) / 100

Working Demo

Milind Anantwar
  • 81,290
  • 25
  • 94
  • 125
0

You can use toFixed(2) to round off values.

use

$('#txtsum').val(unitratesum.toFixed(2));

instead of

$('#txtsum').val(unitratesum);
Mritunjay
  • 25,338
  • 7
  • 55
  • 68