Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

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 digit. How do i tackle with this problem.

Thanks,

iSight

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
183 views
Welcome To Ask or Share your Answers For Others

1 Answer

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...