1

Why do I get Uncaught type error: undefined is not a function"""
I have no J Query in my page

Here is my code:

function CDec(Currency) {
    var number = Currency.replace(/[^0-9\.]+/g,"");
    return number;
}

Calling of the function

SellPrice.value = "$" +  CurrencyFormat(CDec(ListPrice.value * (1 + CDec(Markup.value))) * CDec(Mutiplier.value));

and

Markup.value =   CurrencyFormat(100 * (CDec(SellPrice.value)-CDec(Netcost.value)) / CDec(Netcost.value)) + "%" 
Pieter de Vries
  • 101
  • 2
  • 13

3 Answers3

2

Simply convert numbers that are passed as parameter to string, e.g.:

function CDec(Currency) {
    var number = (Currency + '').replace(/[^0-9\.]+/g,"");
    return number;
}

But I would recommend you to validate input data first.

Kiril
  • 2,935
  • 1
  • 33
  • 41
  • This seems to look like a hack .tosring looks better in my opinion but your code does work. – Pieter de Vries Dec 22 '14 at 18:11
  • 1
    There're lots of ways to convert number to string. And **mostly** adding an empty string is the fastest way. Of course it depends on browser and amount of conversions. See more [here](http://stackoverflow.com/questions/5765398/whats-the-best-way-to-convert-a-number-to-a-string) – Kiril Dec 22 '14 at 18:14
2
function CDec(Currency) {
    Currency = Currency.toString();
    var number = Currency.replace(/[^0-9\.]+/g,"");
    return number;
}
hjl
  • 2,794
  • 3
  • 18
  • 26
1

Given your comments you would be better off replacing known possible characters and validating the return result.

function CDec(Currency) {
    if (typeof Currency !== "number")
        Currency = parseFloat(Currency.toString().replace(/[£$%]/g, ""));

    return Currency;
}

console.log( CDec(1.22) );
console.log( CDec(-1.22) );
console.log( CDec("$1.22") );
console.log( CDec("$1.22%") );
console.log( CDec("-£1.22") );

if (isNaN(CDec("Woof"))
   alert("invalid!");

You should also probably scale your values: Precise Financial Calculation in JavaScript. What Are the Gotchas?

Community
  • 1
  • 1
Alex K.
  • 171,639
  • 30
  • 264
  • 288