【问题标题】:Can I move a decimal in javascript without math?我可以在没有数学的情况下在javascript中移动小数吗?
【发布时间】:2012-04-20 02:17:49
【问题描述】:

我希望能够在不使用数学的情况下在未知数量的数字上移动小数点 2 位。我知道这看起来很奇怪,但有限的精度会导致一些变化。我的 javascript 不强,但我真的很想学习如何切分一个数字,并在可能的情况下这样做。所以,我希望你们很棒的人能提供帮助。

问题:

  • 575/960 = 0.5989583333333334 使用控制台
  • 我想将其复制和粘贴百分比,例如:59.89583333333334%
  • 如果我使用数学并乘以 100,由于精度有限,它会返回 59.895833333333336

有没有办法让它成为一个字符串,并且总是将小数点向右移动 2 位以跳过数学?

这也是一个小提琴,代码:http://jsfiddle.net/dandenney/W9fXz/

如果您想知道我为什么需要它并想要精确度,这是我制作的这个小工具,用于在不使用计算器的情况下获得响应百分比:http://responsv.com/flexible-math

【问题讨论】:

  • 不要忘记您使用的 Web 浏览器的显示器可能小于 4K x 4K 像素。对于任何计算,大概五六位数的精度就足够了,对吧?
  • 你考虑过toFixed吗?例如(575 / 960).toFixed(4) 将是 0.5989(作为字符串)。这可能更容易使用(更不用说更漂亮了)。
  • 数学真的很简单,为什么要跳过它?每次var numb = 0.123; var newNumb = numb/100 时,您可以轻松地使用除以 100 将其向左跳 2 个空格。我的意思是,这真的那么难吗?
  • 如果它是一个字符串,您只需在其上使用 parseFloat newNumb = parseFloat(numb)/100; 这根本不是任何数学运算
  • @SpYk3HH 我通常会跳过这个,但你用“我的意思是,那真的有那么难吗?我有一秒钟的感觉很愚蠢,但后来读到你在没有真正阅读问题的情况下就抨击了我。除法会走向相反的方向,而乘法会遇到我提到的有限精度问题。所以,var numb = 575/960; newNumb = parseFloat(numb)*100;控制台.log(newNumb); > 59.895833333333336 我不擅长 JS,并试图解释我的推理。如果你没有耐心,我建议跳过菜鸟的问题。

标签: javascript decimal


【解决方案1】:

如果原始数字是这种已知结构,并且小数点右边总是至少有两位,你可以这样做:

function makePercentStr(num) {
    var numStr = num + "";
    // if no decimal point, add .00 on end
    if (numStr.indexOf(".") == -1) {
        numStr += ".00";
    } else {
        // make sure there's at least two chars after decimal point
        while (!numStr.match(/\.../)) {
            numStr += "0";        
        }
    }
    return(numStr.replace(/\.(..)/, "$1.")
           .replace(/^0+/, "")    // trim leading zeroes
           .replace(/\.$/, "")    // trim trailing decimals
           .replace(/^$/, "0")    // if empty, add back a single 0
           + "%");
}

测试用例的工作演示:http://jsfiddle.net/jfriend00/ZRNuw/

【讨论】:

  • 但它不适用于 4/2。因为“2”变成了 2 而不是 200%。
  • 谢谢,这绝对有效!对于我这样做的方式,我必须先将其转换为字符串,然后是 BOOM!
  • 就像我在回答的第一句话中所说的那样 - 它适用于小数点右侧有两位数字的数字,就像他们询问的数字一样。如果它需要适用于所有可能的输入数字,那么它可以变得更智能。
  • @DanDenney - 好的,我已经修改了答案以使用任何带或不带小数的输入数字,小数点右侧有或没有足够的数字。
  • @jfriend00 这太棒了,它可以帮助那些在搜索时偶然发现这个问题的人。不过,您的原始答案非常适合我的需要。非常感谢!
【解决方案2】:

该问题要求在没有数学的情况下解决问题,但以下解决方案涉及数学。我把它留作参考

function convertToPercentage(num) {
    //Changes the answer to string for checking
    //the number of decimal places.
    var numString = num + '';
    var length = (numString).substring(numString.indexOf(".")+1).length;

    //if the original decimal places is less then
    //no need to display decimals as we are multiplying by 100
    //else remove two decimals from the result
    var precision = (length < 2 ? 0 : length-2);

    //if the number never contained a decimal. 
    //Don't display decimal.
    if(numString.indexOf(".") === -1) {
         precision = 0;   
    }        
    return (num * 100).toFixed(precision) + "%";
}        

Working jsFiddle 这里的测试用例与accepted answer 相同。

【讨论】:

    【解决方案3】:

    我使用这种方法是因为有浮动错误的风险:

    const DECIMAL_SEP = '.';
    
    function toPercent(num) {
      const [integer, decimal] = String(num).split(DECIMAL_SEP);
    
      // no decimal, just multiply by 100
      if(typeof decimal === 'undefined') {
        return num * 100;
      }
    
      const length = decimal.length;
    
      if(length === 1) {
        return Number(integer + decimal + '0');
      }
    
      if(length === 2) {
        return Number(integer + decimal);
      }
    
      // more than 2 decimals, we shift the decimal separator by 2
      return Number(integer + decimal.substr(0, 2) + DECIMAL_SEP + decimal.substr(2));
    }
    
    console.log(toPercent(10));
    console.log(toPercent(1));
    console.log(toPercent(0));
    console.log(toPercent(0.01));
    console.log(toPercent(0.1));
    console.log(toPercent(0.12));
    console.log(toPercent(0.123));
    console.log(toPercent(12.3456));

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2015-05-26
      • 2019-03-22
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2010-11-23
      • 1970-01-01
      相关资源
      最近更新 更多