Rob
Rob

Reputation: 235

Unexpected result adding numbers: "79.0014.95", why?

So I have a script that grabs a <tr> and iterates through it to get all the vars I need using jquery. One of those is a price, where the text of that td is 79.00 So I grab that and store it as var price. I now need to add that to another number that I decide, let's say 14.95. What I thought would work was

var val1 = parseInt(price);
val1 = val1.toFixed(2);
var sub = val1 + 14.95;

but that outputs 79.0014.95 it's just concatenating them as if it were a string. Here's a the code I am using.

$("#phrases tbody tr").live('click', function() {
            var nTds = $('td', this);
            var phrase = $(nTds[0]).text();
            var phrase_id = $(nTds[0]).attr("name");
            var searches = $(nTds[4]).text();
            var price = $(nTds[5]).text(); //is 79.00
            var val1 = parseInt(price);
            val1 = val1.toFixed(2);
            var val2 = 14.95;
            val2 = val2.toFixed(2);
            var sub = val1 + val2;

now when sub is output it is 79.0014.95. Any help would be greatly appreciated as this is driving me nuts. Thank you.

Upvotes: 0

Views: 122

Answers (4)

nnnnnn
nnnnnn

Reputation: 150050

The + operator will do string concatenation if either operand is a string. The toFixed() method returns a string representation of a number. Hence the result you are getting.

You need to do your calculations first and then call toFixed() on the final result.

Also, why are you using parseInt() when dealing with prices that could (presumably) have something other than 0 after the decimal point? You probably need parseFloat(), or you can convert a string to a number using the unary + operator (var n = (+"123.32");).

Upvotes: 1

Adam Zalcman
Adam Zalcman

Reputation: 27233

Number.toFixed() method formats the number and returns its string representation.

JavaScript's + operator does concatenation whenever at least one of the operands is a string.

You should do formatting once all arithmetic has been performed.

Upvotes: 1

Dave Newton
Dave Newton

Reputation: 160211

toFixed() returns a string.

Do the padding after you do the math.

Upvotes: 0

Alex Wayne
Alex Wayne

Reputation: 187074

toFixed() returns a string. And "string" + anything equals "stringanything".

var a = (123).toFixed(2);
var b = a + 123;
console.log(b); // "123.00123"

var c = 123;
var d = c + 123;
console.log(d.toFixed(2)); // "246.00"

So do the toFixed() after you add the numbers together, not before.

Upvotes: 2

Related Questions