javascript - 以 10 为基数四舍五入

标签 javascript math number-manipulation

我有一个函数可以将提供给该函数的数字四舍五入到最接近的整数便士。

<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/

相关文章:

javascript - 如何拦截 Javascript 函数中的网络服务器响应

java - Java 中的 Math.sin 和 Math.cos 发生了什么?以及如何修复它?

batch-file - 批处理 : Reordering numbers in a text file

javascript - 获取给定系列的倒序数

javascript - 如何访问正在循环的表的 <td> 元素内的元素?

javascript - 无法使用 Chrome 扩展程序添加响应 header

javascript - 如何提取与某些模式不匹配的数字?

python - 如何通过python计算属于字符串列表的每个字符串长度?

java - 在java中获取下一个更高的整数值