JS中的数学 - 如何从百分比中获得比率

Osc*_*son 1 javascript math rounding fractions

我正在尝试制作一个转换器,但我不知道这样做的公式,例如,我如何得到30711152的85694的比率.所以,我可以得到像85694/30711152*100 = 0.28的% (四舍五入)但是如何在100中获得类似1的比例?我相信大概是1:400左右?但我不知道如何准确地使用它或使用什么配方......

rec*_*ive 5

比例为1英寸30711152 / 85694.只需反转分数.


小智 5

我意识到这已经很老了,但我最近遇到了这个问题。我需要给出给定人群的两个部分的关系,其中数字可能非常大,但需要简化的比例,例如 3:5 或 2:7。我想出了这个并希望它有帮助:

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}`
}
Run Code Online (Sandbox Code Playgroud)
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}
Run Code Online (Sandbox Code Playgroud)
<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>
Run Code Online (Sandbox Code Playgroud)