Click here to Skip to main content
15,892,927 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
function formatAmount() {
	return "$" + amount.toFixed( 2 );
}

var amount = 99.99;
var kk = 11.11;

amount = formatAmount();
kk = formatAmount(); //TypeError: amount.toFixed is not a function (line 2 in function formatAmount)

console.log(amount); //"$99.99"


What I have tried:

I have two questions:

1.
Why it is OK to assign function formatAmount() to amount but not OK to do so to kk?

2.
If I assign function formatAmount() to amount, then the value of amount is no longer 99.99, right? Then why the output of amount.toFixed( 2 ) in console.log(amount) is still 99.99?
Posted
Updated 24-Nov-17 0:23am
v2

1 solution

function formatAmount() {
	return "$" + amount.toFixed( 2 );
}
 
var amount = 99.99; // amount is 99.99 so is numeric
var kk = 11.11;
 
amount = formatAmount(); // after formatAmount amount is "$99.99" so is string
kk = formatAmount(); // you are now trying to use toFixed on a string which you can't do, it worked before because amount was numeric before 


You should change your formatAmount function so that it takes the value to format as a param rather than acting on a global variable.

function formatAmount(a) {
    return "$" + a.toFixed(2);
}

var amount = 99.99;
var kk = 11.11;

var amountF = formatAmount(amount);
var kkF = formatAmount(kk);

console.log(amountF); 
console.log(kkF);
 
Share this answer
 
Comments
CPallini 24-Nov-17 9:12am    
5.

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900