开发者

Math in JS - How do I get a ratio from a percentage

I'm trying to make a converter, but i don't know the formula to do th开发者_如何学Pythonis, for example, how do I get the ratio of 85694 of 30711152. So, i can get the % like 85694/30711152*100=0.28 (rounded) but how do I then get the ratio of like 1 in a 100? I believe that'd be around 1:400? But i don't know how to get it exactly or what formula to use...


The ratio is 1 in 30711152 / 85694. Just invert the fraction.


I realize this is VERY old, but I ran into this question recently. I needed to to give the relationship two segments of a given population, where the numbers could be quite large, but the need was for a simplified ratio such as 3:5 or 2:7. I came up with this and hope it's helpful:

function getRatio(a, b, tolerance) {

  /*where a is the first number, b is the second number,  and tolerance is a percentage 
  of allowable error expressed as a decimal. 753,4466,.08 = 1:6, 753,4466,.05 = 14:83,*/

  if (a > b) {
    var bg = a;
    var sm = b;
  } else {
    var bg = b;
    var sm = a;
  }
  for (var i = 1; i < 1000000; i++) {
    var d = sm / i;
    var res = bg / d;
    var howClose = Math.abs(res - res.toFixed(0));
    if (howClose < tolerance) {
      if (a > b) {
        return res.toFixed(0) + ':' + i;
      } else {
        return i + ':' + res.toFixed(0);
      }
    }
  }
}















// Ignore this below

const compute = () => {
  const a = parseInt(document.getElementById('a').value) || 1,
    b = parseInt(document.getElementById('b').value) || 1,
    tolerance = parseInt(document.getElementById('tol').value) / 10 || 1
  document.getElementById('output').innerHTML= `${a} / ${b} | <strong>${getRatio(a,b,tolerance)}</strong> | tolerance: ${tolerance}`
}
input{border-radius:5px;border:.5px solid #000;padding:10px}p{font-family:system-ui;font-size:18pt;padding-left:20px}strong{font-size:36pt}
<div> <input id="a" oninput="compute()" placeholder="Enter first number"/> <input id="b" oninput="compute()" placeholder="Enter second number"/> <input id="tol" oninput="compute()" placeholder="Tolerance" type="number" min="1" max="10"/> <p id="output"></p></div>


Well, the ratio stays constant. If you have the ratio 3:12, it is equivalent to the ratio 1:4, which in turn equates to 25%.

So 85694 : 30711152 = 1 : 358.381.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜