我有一个函数可以将提供给该函数的数字四舍五入到最接近的整数便士。
<script type='text/javascript'>
Math.roundNumber = function(a,b){
if(!isNaN(parseInt(a))){
c = Math.pow(10,b);
return (Math.round(a*c)/c);
}
return false;
}
</script>
但是我注意到,输入到函数中的所述数字只能四舍五入到最接近的一便士,但必须四舍五入到小数点后两位。
例如
15.236562213541684 would = 15.24 9846.65456169846 would = 9846.66
I thought it would just be a case of changing return (Math.round(ac)/c); To return (Math.ceil(ac)/c);
Obviously I was very wrong.
Any help on this matter?
** EDIT **
Here is the formula that I'm trying to achieve maybe it'll help
a = intrest price
b = terms
c = a/b
d = c*(b-1)
e = a-d
例如
a = 295.30
b = 156
c = 295.30/156 = 1.90 (rounded up to nearest decimal as above)
d = 1.90 * (b-1) = 294.50
e = 295.30 - 294.50 = 0.80
任何人都可以授权一个功能来执行上述操作吗?
Here 是我当前代码的链接,包括公式...这是我第一次启动 JavaScript 时制作的一个非常古老的公式(现在已经有一段时间了)但是我现在仍然没有好转,因为我那时。
谁能清理它看看他们是否能明白为什么它不能与上面的功能相匹配?
最佳答案
已经有一个内置函数 Number.toFixed(numDigits)
,为什么不使用它呢?
Parameter: digits
The number of digits to appear after the decimal point; this may be a value between 0 and 20, inclusive, and implementations may optionally support a larger range of values. If this argument is omitted, it is treated as 0.Returns:
A string representation of number that does not use exponential notation and has exactly digits digits after the decimal place. The number is rounded if necessary, and the fractional part is padded with zeros if necessary so that it has the specified length. If number is greater than 1e+21, this method simply calls Number.toString() and returns a string in exponential notation.
例子:
>>> new Number(15.236562213541684).toFixed(2);
"15.24"
>>> new Number(9846.65456169846).toFixed(2);
"9846.65"
最后一个与您的示例不匹配 - 9846.65456169846
四舍五入到小数点后两位应该是 9846.65
,而不是 9846.66
。
关于javascript - 以 10 为基数四舍五入,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1505108/