0

I've got three variables I'm trying to sum the values. For two of these items, I need the form value to read differently, so i've created an attribute cost to pull the cost through with. My code is:

var opt1 = parseFloat($('#ac1 option:selected').attr('cost')).toFixed(2);
var opt2 = parseFloat($('#ac2 option:selected').attr('cost')).toFixed(2);
var base = parseFloat($('#original_price').val());
var newprice = opt1+opt2+base;

if opt1 should be 4.00, opt2 6.50 and base 10.00, it's giving me an output of 4.006.5010.00 instead of 20.50

any ideas on where i'm going wrong?

TH1981
  • 3,105
  • 7
  • 42
  • 78
  • 4
    `toFixed` returns a string (so `opt1` and `opt2` contain strings) and [don't make financial calculations with floating points numbers](http://stackoverflow.com/questions/2876536/precise-financial-calculation-in-javascript-what-are-the-gotchas). – Felix Kling Sep 05 '11 at 22:03
  • 1
    @Felix Thanks - Good advice for a website I'm writing. – Bojangles Sep 05 '11 at 22:07

1 Answers1

2

Is your toFixed method turning the number into a string? It must be. Try wrapping parseFloat around the entire call.

var newprice = parseFloat(opt1)+parseFloat(opt2)+base;

Also, try testing if opt1 and opt2 are strings

console.log(typeof opt1 === 'string');
Trevor
  • 11,269
  • 2
  • 33
  • 40
  • 1
    yep, that did it. my javascript is still a bit rough. hadn't fully appreciated how toFixed worked. Thanks muchly! – TH1981 Sep 06 '11 at 01:08