简体   繁体   English

如何使用Javascript计算小数点后的数字?

[英]How to count digits after the decimal point with Javascript?

What do I have to change in the following code, so that the amount of digits after the decimal point is shown below the number?下面的代码需要改什么,小数点后的位数显示在数字下面?

 var operator = ['/']; function F1() { answer = document.getElementById("answer"); digits = document.getElementById("digits after decimal point"); rZ1 = Math.floor((Math.random() * 10)); rZ2 = Math.floor((Math.random() * 10) + 1); op = operator[Math.floor(Math.random() * 1)]; var a = parseFloat(eval(rZ1 + op + rZ2).toFixed(3)); var d = 3 if (a.toFixed(2) == a) { a = parseFloat(a.toFixed(2)); var d = 2; if (a.toFixed(1) == a) { a = parseFloat(a.toFixed(1)); var d = 1; } } answer.innerHTML = a; digits.innerHTML = d; }
 <button onclick="F1()"> New </button> <p> <label id="answer"> </label> </p> <label id="digits after decimal point"> </label>

You can just locate where the decimal point is with indexOf您可以使用indexOf找到小数点的位置

 var operator = ['/']; function F1() { answer = document.getElementById("answer"); digits = document.getElementById("digits after decimal point"); rZ1 = Math.floor((Math.random() * 10)); rZ2 = Math.floor((Math.random() * 10) + 1); op = operator[Math.floor(Math.random() * 1)]; var a = parseFloat(eval(rZ1 + op + rZ2).toFixed(3)); var d = Math.max(0, (a+"").length - (a+".").indexOf(".") - 1); answer.textContent = a; digits.textContent = d; }
 <button onclick="F1()"> New </button> <p> <label id="answer"> </label> </p> <label id="digits after decimal point"> </label>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM