将变量值保存为百分比

时间:2017-01-10 15:27:13

标签: javascript html

我正在尝试将变量值设为百分比,但我不知道该怎么做。这就是我所拥有的:

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%。有没有办法解决这个问题,或解决它?

6 个答案:

答案 0 :(得分:6)

&#13;
&#13;
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;
&#13;
&#13;

答案 1 :(得分:2)

应该是,

Math.floor((y / x) * 100 + "%";

这是一个有效的演示: https://jsfiddle.net/pwnt08qj/

希望这有帮助!

答案 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,这样它就会返回百分比值,然后连接“%”

  • 如果x = 50 y = 10
  • 结果= 10/50 = 0.2
  • percentage = results * 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">&rarr; 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>