jQuery calculation NaN
-
13-10-2019 - |
Question
I have a view that output decimal values that represent money data types on the database. To output I am using the following formatting code
string price = String.Format("{0:f}", (item.Price + item.VAT));
that produce a string like this
12,99 (with comma as the decimal separator)
I am now using this string to make some calculation on the client using jQuery
elmProductSelected.children("option").each(function(n) {
var pIdx = $(this).attr("rel");
var pObj = products.eq(pIdx);
var pValue = $(this).attr("value");
var valueArray = pValue.split('|');
var prdId = valueArray[0];
var pQty = valueArray[1];
/* the value of pPrice is 12,99 after the following call */
var pPrice = $(pObj).attr(attrProductPrice);
/* I get NaN here! */
sTotal = sTotal + ((pPrice - 0) * (pQty - 0));
cProductCount++;
cItemCount = cItemCount + (pQty-0);
});
I am getting NaN right on the line I have commented. I suppose that this is due to the fact that the pPrice
value use the comma as the decimal separator because if I manually set it as 12.99
everything works.
Is there a way to read the 12,99
as a number using javascript/jQuery?
Solution
NaN = Not a number
By using parseInt
you can tell Javascript that it should be treated as a number.
var pPrice = parseInt($(pObj).attr(attrProductPrice));
You might need parseFloat
if you're using a decimal.
OTHER TIPS
There are two problems with the code. First, you should cast the string to float, as Webnet suggests. The parseFloat function, however, will expect the argument to use dot as a decimal separator. Therefore, the following code will do what you want:
var pPrice = $(pObj).attr(attrProductPrice);
pPrice = parseFloat(pPrice.replace(',', '.'));
First, you replace the comma for a dot, then convert the result to a float.
If that's the only comma separator there will be (none for a thousands separator), then just replace it.
var num = parseInt( str.replace( ',', '.' ) ); // or parseFloat
If there are other characters that will prevent correct parsing, then I'd suggest having a custom attribute that stores the undecorated number.
<input data-undecorated="123.45" value="123,45" />
var num = parseInt( $('#myInput').data('undecorated') ); // or parseFloat
You can use data()
like this to get data-
attributes if you're using jQuery 1.4.3
or later.
try this
var pPrice = $(pObj).attr(attrProductPrice).split(",").join(".");
Try this RegEx:
Update: Changed the expression, since I missed the part(with comma as the decimal separator).
var pPrice = $(pObj).attr(attrProductPrice)..replace(/(,)(\d+)$/, ".$2").replace(",","")
This looks related: How to convert string into float in javascript?
It looks like you'll have to replace the comma with a decimal.
parseFloat('12,99'.replace(',', '.'))