0

Im trying to round a number to 2 decimal place. I have tried the following but not having any luck? Can somebody please help me and tell me where im going wrong??

var winPercentage = totalWins/(totalWins+totalLost)*100;
winPercentage.toFixed(2);
document.getElementById('win-percentage').innerHTML = winPercentage + " %";

i search and tried this but to be honest i have no idea what it is?

var winPercentage = totalWins/(totalWins+totalLost)*100;
expr {double(round(100*winPercentage))/100}
document.getElementById('win-percentage').innerHTML = winPercentage + " %";
lky
  • 1,081
  • 3
  • 15
  • 31
  • Can you give an example of input and and expected output because your code is correct for what you have asked. – roshan Mar 04 '15 at 20:49
  • I cant seem to get it to work? its displaying numbers like 48.38709677419355 % When i would like 48.38 – lky Mar 04 '15 at 20:53
  • and when its 40.5 i want it round to 40.50? – lky Mar 04 '15 at 20:54

2 Answers2

1

Try to use the following syntax instead and alter it to your needs

var num = 5.1;

num.toFixed(2); //will become 5.10
Mureinik
  • 297,002
  • 52
  • 306
  • 350
natali
  • 90
  • 1
  • 10
  • var winPercentage = totalWins/(totalWins+totalLost)*100;winPercentage.toFixed(2); document.getElementById('win-percentage').innerHTML = winPercentage + " %"; – lky Mar 04 '15 at 20:52
  • var winPercentage = totalWins/(totalWins+totalLost)*100;winPercentage.toFixed(2); document.getElementById('win-percentage').innerHTML = winPercentage + " %"; – lky Mar 04 '15 at 20:52
0

You had the right idea with toFixed(2). The problem is that it returns the formatted number, it does not alter the variable it was called on. In other words, you just need to assign it back the the variable you were using:

winPercentage = winPercentage.toFixed(2);
Mureinik
  • 297,002
  • 52
  • 306
  • 350