簡體   English   中英

如何使用Javascript計算小數點后的數字?

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

下面的代碼需要改什么,小數點后的位數顯示在數字下面?

 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>

您可以使用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