Reputation: 375
var sssee = "581.30";
var ssser = "1,178.70";
var ssee = sssee.trim().replace(/,/g, "");
var sser = ssser.trim().replace(/,/g, "");
console.log("ee " + ssee)
console.log("er " + sser)
console.log("total " + parseFloat(ssee + sser))
In log i see:
ee 581.30
er 1178.70
total 581.301178
Why is it when adding replace to remove the ,
messes the computation.
Upvotes: 0
Views: 108
Reputation: 1499
Variables ssee
and sser
are both strings. When you peform ssee + sser
it would return string 581.301178.70
which would be passed to parseFloat
function then. When there are two decimal points, only first is taken as correct, that's why parseFloat
returns 581.301178
.
Check the snippet with correct solution.
var sssee = 581.30;
var ssser = "1178.70";
var ssee = String(sssee).trim().replace(/,/g, "");
var sser = String(ssser).trim().replace(/,/g, "");
console.log("ee " + ssee)
console.log("er " + sser)
console.log("total " + (parseFloat(ssee) + parseFloat(sser)))
You should also wrap ssee
and ssser
in String
object before using trim
and replace
methods. Without doing that if you provide those variables as floats, instead of strings, your code won't work.
Upvotes: 7
Reputation: 3310
Your problem:
You concatenate two strings ("581.30" + "1,178.70") to one string ("581.301178.70"). Then you parse it to a float (581.301178).
Solution:
You need to parse each one to a float at first. After do your addition (parseFloat(ssee) + parseFloat(sser)
).
Upvotes: 1