我正在尝试将变量值设为百分比,但我不知道该怎么做。这就是我所拥有的:
var x = 50;
var y = 10;
function myFunction(){
document.getElementById("paragraph").innerHTML = y/x;
}
<button onclick="myFunction()">Click Me!</button>
<p id="paragraph"></p>
虽然它显示为0.2,而不是20%。有没有办法解决这个问题,或解决它?
答案 0 :(得分:6)
var x = 50;
var y = 10;
function myFunction(){
document.getElementById("paragraph").innerHTML = y/x*100 + "%";
}
&#13;
<button onclick="myFunction()">Click Me!</button>
<p id="paragraph"></p>
&#13;
答案 1 :(得分:2)
答案 2 :(得分:0)
10/50 = 0.2 - 或者您期望什么?这是一个简单的数学运算。如果您想要百分比值,则乘以100并舍入(如果需要)
var x = 50;
var y = 10;
function myFunction(){
document.getElementById("paragraph").innerHTML = Math.round(y/x * 100);
}
答案 3 :(得分:0)
只需将除法结果乘以100,这样它就会返回百分比值,然后连接“%”
function displayPercentage() {
var x = document.getElementById("x").value;
var y = document.getElementById("y").value;
document.getElementById("paragraph").innerHTML = Math.round((x / y) * 100) + "%";
}
<lable>x:</lable><input type="number" id="x">
<lable>y:</lable><input type="number" id="y">
<button onclick="displayPercentage()">Click Me!</button>
<p id="paragraph"></p>
答案 4 :(得分:0)
只需将结果乘以100并连接&#39;%&#39; document.getElementById(&#34; paragraph&#34;)。innerHTML = y / x * 100 +&#34;%&#34 ;;
答案 5 :(得分:0)
这是将价值节省成百分比的代码
function unitCount () {
var userUnit = document.getElementById("eUnit").value;
var _50 = 0.50;
var _100 = 0.70;
var _200 = 1.20;
var _250 = 1.50;
// var addCharge = 20%;
var first50 = 50;
var first100 = 100;
var first200 = 200;
var first250 = 250;
if (userUnit <= first50) {
var total = userUnit * _50;
total = Math.round(total * 20);
var _total = total/100;
console.log(_total+"%");
}
}
<h6>03 - Electricity unit charge</h6>
<label for="second">→ Unit Input:</label>
<input type="text" class="form-control" id="eUnit" placeholder="Enter Electricity Units"><br>
<button type="button" class="btn btn-dark" onclick="unitCount()">Check Unit Cost</button>
<p id="resultUnit"></p>