------------------------------------------------------------
// 函数 : StrToFloatW
// 功能 : 将一个字符串转换为浮点数
// 返回值 : float
// 参数 : char* pstrfloat
// 附注 :
// -------------------------------------------------------------------------
float StrToFloatW(wchar_t* pstrfloat)
{
// check
if (!pstrfloat)
{
return 0.0;
}
bool bNegative = false;
bool bDec = false;
wchar_t* pSor = 0;
wchar_t chByte = L'0';
float fInteger = 0.0;
float fDecimal = 0.0;
float fDecPower = 0.1f;
// 进行首位判断,判断是否是负数
if (pstrfloat[0] == L'-')
{
bNegative = true;
pSor = pstrfloat + 1;
}
else
{
bNegative = false;
pSor = pstrfloat;
}
while (*pSor != L'\0')
{
chByte = *pSor;
if (bDec)
{
// 小数
if (chByte >= L'0' && chByte <= L'9')
{
fDecimal += (chByte - L'0') * fDecPower;
fDecPower = fDecPower * 0.1;
}
else
{
return (bNegative -(fInteger + fDecimal): fInteger + fDecimal);
}
}
else
{
// 整数
if (chByte >= L'0' && chByte <= L'9')
{
fInteger = fInteger * 10.0 + chByte - L'0';
}
else if (chByte == L'.')
{
bDec = true;
}
else
{
return (bNegative -fInteger : fInteger);
}
}
pSor++;
}
return (bNegative -(fInteger + fDecimal): fInteger + fDecimal);
}
// -------------------------------------------------------------------------
// $Log: $
测试用例:
// StringToFloatShell.cpp : Defines the entry point for the console application.
//
#include "stdafx.h"
#include "StringToFloat.h"
int _tmain(int argc, _TCHAR* argv[])
{
float aaaa = 0;
aaaa = StrToFloat(L"12.34");
aaaa = StrToFloat(L"a23");
aaaa = StrToFloat(L"1234");
aaaa = StrToFloat(L"12.34");
aaaa = StrToFloat(L"12.34.56");
aaaa = StrToFloat(L".34");
aaaa = StrToFloat(L"34a");
aaaa = StrToFloat(L"34a.456");
aaaa = StrToFloat(L"-34");
aaaa = StrToFloat(L"-56.34");
aaaa = StrToFloat(L"-3.45.67");
aaaa = StrToFloat(L"-.45.6a");
aaaa = StrToFloat(L"-.");
aaaa = StrToFloat(L"-0");
return 0;
}
大家可以再找找BUG。
[END]
摘自 magictong的专栏