[英]Decimals of a string calculation
I have this javascript code for a quiz programme but i can't figure out how to return the calculation result of the last context line with only 1 decimal. 我有一个用于测验程序的javascript代码,但是我不知道如何仅用1个小数返回最后一个上下文行的计算结果。 Any suggestions ?
有什么建议么 ?
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
Directly from W3schools: 直接来自W3schools:
Convert a number into a string, keeping only two decimals: 将数字转换为字符串,仅保留两个小数:
var num = 5.56789;
var n=num.toFixed(2);
The result of n will be: n的结果将是:
5.57 5.57
the rest is left as an exercise for the reader :-) 其余的留给读者练习:-)
Here is a functional function that can truncate decimals: 这是一个可以截断小数的功能函数:
truncateDecimal = function(decimal, numDecimals) {
var decString = ""+decimal;
var dotIndex = decString.indexOf(".");
var numChars = dotIndex + 1 + numDecimals;
return parseFloat(decString.substring(0, numChars));
}
Now truncateDecimal(3010101.234, 1);
现在
truncateDecimal(3010101.234, 1);
returns 3010101.2
. 返回
3010101.2
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.