Question

I am trying to calculate the percentage of two dollar values on a page. I've got the code working in jsFiddle, but whenever I attempt to implement it on my website the code outputs NaN, so I know there must be some issue with my effort to convert the dollar amount to a number I can work with. I don't believe my scripts are conflicting, as I do not receive any errors in the console.

http://jsfiddle.net/f9rGj/

I've highlighted the two numbers I'm trying to calculate in red.

var price1 = $('.Value em.ProductPrice strike').text();
var price2 = $('.YouSave .YouSaveAmount').text();

var number1 = Number(price1.replace(/[^0-9\.]+/g,""));
var number2 = Number(price2.replace(/[^0-9\.]+/g,""));

var savings = (Math.floor((number2 / number1) * 100));

$('#savepercent').text(savings);

Does anyone have any idea as to why this might be spitting out NaN? Maybe I need to try converting the dollar amount some other way?

Thanks to feedback I received, I was able to get this working on my site.

Working code:

var price1 = $('.Value em.ProductPrice strike').text();
var price2 = $('.YouSave .YouSaveAmount').text();


var number1 = parseInt(price1.replace(/[^\d\.]/g, ''));
var number2 = parseInt(price2.replace(/[^\d\.]/g, ''));

var savings = (Math.floor((number2 / number1) * 100));

$('#savepercent').text(savings);
Était-ce utile?

La solution

Use the correct String to Number conversion function:

Number.parseFloat()

The Number.parseFloat() method parses a string argument and returns a floating point number. This method behaves identical to the global function parseFloat and is part of ECMAScript 6 (its purpose is modularization of globals).

or

Number.parseInt()

The Number.parseInt() method parses a string argument and returns an integer of the specified radix or base. This method behaves identical to the global function parseInt and is part of ECMAScript 6 (it's purpose is modularization of globals).

Know your RegEx

You should use \D which means Any non-digit instead of trying to do it yourself.

\[^\D\.\,\] will match any Non-Digits and the . or the , which is used outside the US for a delimiter instead of the ,. See this link.

Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top