[removed] Round to a number of decimal places, but strip extra zeros

前端 未结 8 2190
鱼传尺愫
鱼传尺愫 2020-12-02 12:00

Here\'s the scenario: I\'m getting .9999999999999999 when I should be getting 1.0.
I can afford to lose a decimal place of precision, so I\'m u

8条回答
  •  青春惊慌失措
    2020-12-02 12:18

    There is a better method which keeps precision and also strips the zeros. This takes an input number and through some magic of casting will pull off any trailing zeros. I've found 16 to be the precision limit for me which is pretty good should you not be putting a satellite on pluto.

    function convertToFixed(inputnum)
    {
    
          var mynum = inputnum.toPrecision(16);
    //If you have a string already ignore this first line and change mynum.toString to the inputnum
    
          var mynumstr = mynum.toString();
        return parseFloat(mynumstr);
        }
        alert(convertToFixed(6.6/6));
    

提交回复
热议问题