0

One common question ,may be I am wrong at this point but last two hours on google not give me any answer, Question is how to convert CString to float without using std: library in c++.

I tried with wcstod() function but, This function has very different behaviour. Please find following code,

CString Tempconvert = "32.001";
double TempConvertedValue = wcstod(Tempconvert,NULL);

So, Finally TempConvertedValue should have value 32.001. But i am getting TempConvertedValue = 32.000999999999998 Please provide me any help which convert String "32.001" to float 32.001 only. Without using std: library.

user1781290
  • 2,233
  • 18
  • 25
Santosh Dhanawade
  • 1,670
  • 13
  • 28
  • It looks like there is a float (instead of a double) somewhere. Floats can't express 32.001 exactly but double can. wcstod returns a double tho so the problem shouldn't be there. How do you output the value? – Joel Klinghed Jan 08 '14 at 13:05
  • What's wrong with `std` library? – herohuyongtao Jan 08 '14 at 13:10
  • @JoelKlinghed This is not true, double can't express a floating point value exactly as it uses the same sort of encoding as a float but with more bits so it can hold bigger value and with more precision. – Eric Fortin Jan 08 '14 at 13:14
  • @EricFortin, true, exactly was a bad choice of word here. What I meant is that: float f = 32.001f; double d = 32.001; printf("%f %f", f, d); will print "32.000999 32.001000" ie double has enough precision to keep 32.001 – Joel Klinghed Jan 08 '14 at 13:16
  • @JoelKlinghed thanks for reply first of all 32.001 is a double value. i am just trying to convert string to double.And i am not getting point "How do you output the value?". – Santosh Dhanawade Jan 08 '14 at 13:17
  • @Aryabhata, how do you see the value 32.000999999999998? By printing it? Watching the value in the debugger? – Joel Klinghed Jan 08 '14 at 13:19
  • @JoelKlinghed by tool tip provided by Microsoft visual studio.Watching value in debugger. – Santosh Dhanawade Jan 08 '14 at 13:23

1 Answers1

1

What you see is an example of floating point internal representation. You can have a look here to see how double are stored in memory. See also this question to know why debugger shows you this value.

With this storing format, it is not possible to represent a decimal number exactly. That is why money calculations usually use special decimal types that are either custom or part of the programming language.

Community
  • 1
  • 1
Eric Fortin
  • 7,323
  • 2
  • 23
  • 31