CString TO Double (zz)




//z 2013-10-21 15:01:30 IS2120@BG57IV3 T3345574402.K.F3396121938[T3,L303,R3,V37]
1. atl CString 转换成 double 浮点数
CString can convert to an LPCTSTR, which is basically a const char* (const wchar_t* in Unicode builds).

Knowing this, you can use atof():

CString thestring("13.37");
double d = atof(thestring).

...or for Unicode builds, _wtof():

CString thestring(L"13.37");
double d = _wtof(thestring).

...or to support both Unicode and non-Unicode builds...

CString thestring(_T("13.37"));
double d = _tstof(thestring).

(_tstof() is a macro that expands to either atof() or _wtof() based on whether or not_UNICODE is defined)

//z 2013-10-21 15:01:30 IS2120@BG57IV3 T3345574402.K.F3396121938[T3,L303,R3,V37]
2. 使用 std::stringstream

You can convert anything to anything using a std::stringstream. The only requirement is that the operators >> and << be implemented. Stringstreams can be found in the <sstream> header file.

std::stringstream converter;
converter << myString;
converter >> myDouble;

//z 2013-10-21 15:01:30 IS2120@BG57IV3 T3345574402.K.F3396121938[T3,L303,R3,V37]
3. lexical_cast
#include <boost/lexical_cast.hpp>
using namespace boost;

...

double d = lexical_cast<double>(thestring);

4. strtod

strtod (or wcstod) will convert strings to a double-precision value.

(Requires <stdlib.h> or <wchar.h>)

Example

1
2
3
4
5
6
7
8
9
10
11
12
13
14
/* strtod example */
#include <stdio.h>      /* printf, NULL */
#include <stdlib.h>     /* strtod */

int main ()
{
  char szOrbits[] = "365.24 29.53";
  char* pEnd;
  double d1, d2;
  d1 = strtod (szOrbits, &pEnd);
  d2 = strtod (pEnd, NULL);
  printf ("The moon completes %.2f orbits per Earth year.\n", d1/d2);
  return 0;
}
Output:

The moon completes 12.37 orbits per Earth year.


//z 2014-02-20 16:26:18 IS2120@BG57IV3 T3529903025.K.F3153028746[T372,L4642,R198,V6937]
2. 删除字符串结尾的 0


IS2120@CSDN.BG57IV3 //z 2014-02-20 16:16:02 IS2120@BG57IV3 T707139593 .K.F3153028746[T371,L4620,R198,V6936] void removeTrailingZeros(char pio_cText[]) { char* pCh = strchr(pio_cText,'.'); if(pCh!=NULL) { int iLen = static_cast<int>(strlen(pio_cText)); char* pPos = pio_cText + iLen -1; while(*pPos == '0') { *(pPos--) = '\0'; } if(*pPos == '.') { *pPos= '\0'; } } }IS2120@CSDN.BG57IV3

posted @ 2013-10-21 15:03  BiG5  阅读(532)  评论(0编辑  收藏  举报