1

我有这个用于测验程序的 javascript 代码,但我不知道如何返回最后一个上下文行的计算结果,只有 1 个小数。有什么建议么 ?

EndQuiz=function(){
                  canvas.removeEventListener('click',ProcessClick,false);
                  context.drawImage(quizbg, 0,0,550,90,0,0,550,400);
                  context.font = "20pt Georgia,Arial";
                  context.fillText("Thanks for finishing. ",20,80);
          context.fillText("This is how good you were:",20,120);
                  context.font = "16pt Georgia,Calibri,Arial";
                  context.fillText("Correct answers: "+String(rightanswers)+" of "+String(rightanswers+wronganswers),20,180);

          context.fillText("Correct: "+String(rightanswers/(wronganswers+rightanswers)*100)+"%",20,240);1
4

2 回答 2

1

直接来自 W3schools:

将数字转换为字符串,只保留两位小数:

var num = 5.56789;
var n=num.toFixed(2);

n 的结果将是:

5.57

其余的留给读者练习:-)

于 2013-05-25T12:23:05.160 回答
0

这是一个可以截断小数的函数:

truncateDecimal = function(decimal, numDecimals) {
    var decString = ""+decimal;
    var dotIndex = decString.indexOf(".");
    var numChars = dotIndex + 1 + numDecimals;
    return parseFloat(decString.substring(0, numChars));
}

现在truncateDecimal(3010101.234, 1);返回3010101.2

于 2013-05-25T12:58:15.433 回答