Qt: Roundoff of 12.625 by 2 returns 12.62

China☆狼群 提交于 2021-02-07 19:42:07

问题


I can't get it why the ff code returns 12.62 instead of 12.63

 QDebug << QString::number(12.625, 'f', 2);

and also what will be the solution for this? Currently my solution is this

QDebug << QString::number(12.625 + 0.0001, 'f', 2);

and it will return 12.63.

btw my OS is ubuntu 11.04


回答1:


GCC uses "Round to Even" or "Banker's Rounding" as it's default mode while Visual Studio uses "Round away from Zero"

From the GCC docs: Rounding

This is the default mode. It should be used unless there is a specific need for one of the others. In this mode results are rounded to the nearest representable value. If the result is midway between two representable values, the even representable is chosen. Even here means the lowest-order bit is zero. This rounding mode prevents statistical bias and guarantees numeric stability: round-off errors in a lengthy calculation will remain smaller than half of FLT_EPSILON.

To change the rounding mode, use fesetround(FE_UPWARD) to round upwards. If you aren't using GCC, your compiler will have a similar option.

Rick Regan provides a list of programming environments and their default rounding behaviours. Inconsistent Rounding




回答2:


There is an open bug report for this:

https://bugreports.qt-project.org/browse/QTBUG-38171



来源:https://stackoverflow.com/questions/27436362/qt-roundoff-of-12-625-by-2-returns-12-62

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!