在基地10舍入 [英] rounding in base 10

查看:85
本文介绍了在基地10舍入的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个函数将给定函数的数字舍入到最接近的整数便士。

I have a function to round a number given to the function to the nearest whole pence.

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

但是我注意到输入到函数中的所述数字必须四舍五入到最近的一个便士,但它必须四舍五入到小数点后两位。

however it has come to my attention that the said number inputted into the function must only be rounded up to the nearest one pence however it must be rounded to two decimal places.

EG


15.236562213541684 would = 15.24  
9846.65456169846 would = 9846.66

我认为这只是改变
的情况return(Math.round(a c)/ c);

返回(Math.ceil(a
c)/ c);

I thought it would just be a case of changing return (Math.round(ac)/c); To return (Math.ceil(ac)/c);

显然我错了。

有关此事的任何帮助吗?

Any help on this matter?

**编辑**

这是我试图实现的公式,也许它会帮助

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

任何人都可以让一个函数执行上述操作吗?

can anyone right a function to do the above?

这里是当前代码的链接i包括公式...它是我在第一次启动JavaScript时制作的一个非常古老的公式(现在还不久前)但是我现在仍然没有更好,就像我当时那样。

Here is a link to the current code i have including the formula... its a very old formula that I made when I first started JavaScript (which is a while ago now) however I'm still no better now as I was back then.

任何人都可以清理它,看看它们是否可以看出为什么它不能与上述功能相匹配?

Can anyone clean it up to see if they can see why its not working to match the function above?

推荐答案

function currency_fix(number)
{
    var unfixed_number = Math.ceil(number.toFixed(5) * 100) / 100;
    return unfixed_number.toFixed(2)
}

var a = currency_fix(295.30)
var b = currency_fix(156)
var c = currency_fix(a / b)
var d = currency_fix(c * (b - 1))
var e = currency_fix(a - d)

document.write(
    'a = ' + a + '<br />' +
    'b = ' + b + '<br />' +
    'c = ' + c + '<br />' +
    'd = ' + d + '<br />' +
    'e = ' + e + '<br />'
)

// OUTPUT
//a = 295.30
//b = 156.00
//c = 1.90
//d = 294.50
//e = 0.80

在这种情况下,我得到了你想要的结果。不确定它是否每次都能正常工作但似乎。我肯定会检查它是否正常工作。

I got it to give the results you want in this case. Not sure if it's going to work every time but it seems to. I'd definitely check it works as you want it to first.

这篇关于在基地10舍入的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆