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

Categories

0 votes
194 views
in Technique[技术] by (71.8m points)

c++ - floating point issue

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

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

1 Answer

0 votes
by (71.8m points)

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.

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...