转自: http://blog.csdn.net/magictong/article/details/6900410
/* -------------------------------------------------------------------------
// 文件名 : StringToFloat.cpp
// 创建者 : magictong
// 创建时间 : 2011-9-6 14:14:02
// 功能描述 :
//
// $Id: $
// -----------------------------------------------------------------------*/
#include "stdafx.h"
#include "StringToFloat.h"
// -------------------------------------------------------------------------
#pragma warning(disable:4244)
// -------------------------------------------------------------------------
// 函数 : StrToFloatA
// 功能 : 将一个字符串转换为浮点数
// 返回值 : float
// 参数 : char* pstrfloat
// 附注 :
// -------------------------------------------------------------------------
float StrToFloatA(char* pstrfloat)
{
// check
if (!pstrfloat)
{
return 0.0;
}
bool bNegative = false;
bool bDec = false;
char* pSor = 0;
char chByte = '0';
float fInteger = 0.0;
float fDecimal = 0.0;
float fDecPower = 0.1f;
// 进行首位判断,判断是否是负数
if (pstrfloat[0] == '-')
{
bNegative = true;
pSor = pstrfloat + 1;
}
else
{
bNegative = false;
pSor = pstrfloat;
}
while (*pSor != '\0')
{
chByte = *pSor;
if (bDec)
{
// 小数
if (chByte >= '0' && chByte <= '9')
{
fDecimal += (chByte - '0') * fDecPower;
fDecPower = fDecPower * 0.1;
}
else
{
return (bNegative? -(fInteger + fDecimal): fInteger + fDecimal);
}
}
else
{
// 整数
if (chByte >= '0' && chByte <= '9')
{
fInteger = fInteger * 10.0 + chByte - '0';
}
else if (chByte == '.')
{
bDec = true;
}
else
{
return (bNegative? -fInteger : fInteger);
}
}
pSor++;
}
return (bNegative? -(fInteger + fDecimal): fInteger + fDecimal);
}
// -------------------------------------------------------------------------
// 函数 : 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: $