字符串计算的小数

时间:2013-05-25 12:14:37

标签: javascript decimal

我有一个测验程序的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

2 个答案:

答案 0 :(得分:1)

直接来自W3schools:

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

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

n的结果将是:

5.57

其余部分留给读者练习: - )

答案 1 :(得分: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