floating point issue

前端 未结 4 1851
醉梦人生
醉梦人生 2020-12-12 07:19

I have a floating value as 0.1 entering from UI.

But, while converting that string to float i am getting as 0.10...01. The problem is the appending of non zero dig

4条回答
  •  春和景丽
    2020-12-12 08:02

    You need to do some background reading on floating point representations: http://docs.sun.com/source/806-3568/ncg_goldberg.html.

    Given computers are on-off switches, they're storing a rounded answer, and they work in base two not the base ten we humans seem to like.

    Your options are to:

    • display it back with less digits so you round back to base 10 (checkout the Standard library's header, and setprecision)
    • store the number in some actual decimal-capable object - you'll find plenty of C++ classes to do this via google, but none are provided in the Standard, nor in boost last I looked
    • convert the input from a string directly to an integral number of some smaller unit (like thousandths), avoiding the rounding.

提交回复
热议问题