彩车四舍五入非精确再presentation [英] Rounding floats with non-exact representation

查看:131
本文介绍了彩车四舍五入非精确再presentation的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我们有一个问题,浮点数对于一些财务计算的四舍五入。

We have a problem with rounding of floating point numbers for some financial calculations.

基本上,我们想要一轮货币数额喜欢1000000000.555到2位小数。然而,浮子再此数目的presentation是1000000000.5549999并且作为结果,我们将四舍五入到1000000000.55而不是正确1000000000.56

Basically, we want to round monetary amounts like 1000000000.555 to 2 decimals. However, the float representation of this number is 1000000000.5549999 and as a result we will round down to 1000000000.55 rather than the correct 1000000000.56.

有什么办法我们可以得出在一个安全的方式解决这个问题?我们已经提出了迄今为止唯一的事情就是舍入操作之前最小的重presentable浮动总是添加量,但我们不知道这是不是在所有情况下的安全。

Is there any way we can come around this problem in a safe way? The only thing we have come up with so far is to always add the smallest representable float to the amount before the rounding operation, but we don't know if this is safe in all cases.

在code是用C语言编写,并需要在WINDOWS32 / 64 / Linux / Solaris上运行,所以我们很遗憾没有获得很好的东西,如在.NET中的十进制数据类型。

The code is written in C and need to run on windows32/64/linux/solaris so we unfortunately do not have access to nice stuff like the Decimal datatype in .net.

任何投入将是有益的。

谢谢,
里卡德

Thanks, Rickard

推荐答案

的正确方法重新present货币最常使用的整数。例如,在欧洲区一个常用的方法是在微欧元(1E-6)重新present值。你会很明显使用64位数学这一点。你会一直使用这个整个应用程序。只有在人类的I / O你会圆的,你会通过10000除以美分,得到一个整数金额这么做。

The proper way to represent currencies most often is using integers. For instance, in the Euro zone a common approach is to represent values in micro-euro's (1E-6). You'd obviously use 64 bits math for this. You'd consistently use this throughout the application. Only on human I/O would you round, and you would do so by dividing by 10000 to get an integer amount in cents.

这篇关于彩车四舍五入非精确再presentation的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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