我正在自学JavaScript,并且遇到了toFixed()方面的问题。我正在研究一个摊销计算器,其中一个步骤返回一个具有大量小数位的数字。我正试着把它减到小数点4位。请注意,示例代码中包含了大量的解释性HTML。它只有在那里,这样我才能计算出方程的步骤。另外,当我把一个加到很长的数字上时,它会把数字加到科学符号的末尾。
var paymentamount;
var principal=250000;
var interestrate = 4.5;
var annualrate = interestrate/12;
var numberofpayments = 360;
document.write("This is the annuitized interest rate: "+ annualrate +"%");
document.write("<h3> Now we add 1 to the annualized interest rate</h3>");
var RplusOne = annualrate + 1;
document.write("<p> This is One Added to R: " + RplusOne + "%");
document.write("<h3>Next RplusOne is Raised to the power of N </h3>");
var RRaised = (Math.pow(RplusOne, numberofpayments)).toFixed(4);
document.write("<p>This gives us the following very long number, even thought it shouldn't: " + RRaised);
document.write("<h3>Now we add one to the very long number </h3>");
var RplusOne = RRaised + 1;
document.write("<p>Now we've added one: " + RplusOne);发布于 2014-09-05 14:20:32
来自MDN文档
如果数字大于1e+21,则此方法只需调用Number.prototype.toString()并以指数表示法返回字符串。
问题是您使用4.5作为您的利率,而不是0.045,因此这样做:
Math.pow(4.5 / 12 + 1, 360)给出一个巨大的数字(确切地说,是6.151362770461608e+49或6.15 * 10^49 )。把你的利率改为0.045,你就会得到你所期望的。
至于var RplusOne = RRaised + 1行,这里的问题是,由于toFixed,RRaised是一个字符串。我只会在显示事物时调用toFixed,而不是在任何其他时间;这样做的主要原因是为了避免后续计算中的舍入错误,但是有一个额外的好处,就是变量仍然是数字而不是字符串。
https://stackoverflow.com/questions/25687954
复制相似问题