主要代码如下:
//获取字符串的长度函数(每个汉字2个字节长度)
int GetStringLength(string str)
{
int ret = 0;
int i = 0;
while (auto sss = str[i++] != '\0')
{
ret++;
}
return ret;
}
//double转化为字符串函数
string DoubleToString(double d)
{
bool isNegative = d < 0 ? true : false;
double high, low;
if (isNegative)
{
high = std::ceil(d);
low = high - d;
}
else
{
high = std::floor(d);
low = d - high;
}
std::deque<int> intDeq, decDeq;
int h = (int)high;
if (isNegative)
{
h *= -1; //确保是非负数//
}
if (h < 10)
{
intDeq.emplace_front(h);
}
else
{
while (h > 0)
{
intDeq.emplace_front(h % 10);
h = std::floor(h / 10);
}
}
if (low > 0)
{
int tmp = 15; //确保小数点后15位//
while (low > 0 && tmp-- > 0)
{
decDeq.emplace_back(std::floor(10 * low));
low = 10 * low;
low -= std::floor(low);
}
}
else
{
decDeq.emplace_back(0);
}
std::string retVal;
retVal.resize(intDeq.size() + decDeq.size() + 2);
int i = 0;
for (const auto& e : intDeq)
{
retVal[i++] = e + 48;
}
retVal[i++] = '.';
for (const auto& e : decDeq)
{
retVal[i++] = e + 48;
}
if (isNegative)
{
retVal = "-" + retVal;
}
return retVal;
}
//字符串转换为double函数
double StringToDouble(string str)
{
std::deque<int> intDeq, decDeq;
bool isFindDot = false;
int i = 0;
while (str[i] != '\0')
{
if (str[i] == '.')
{
isFindDot = true;
}
if (str[i] >= '0'&&str[i] <= '9')
{
auto ch = str[i] - 48;
if (isFindDot)
{
decDeq.emplace_back(ch);
}
else
{
intDeq.emplace_front(ch);
}
}
i++;
}
double retVal = 0.0;
i = 0;
for (const auto& e : intDeq)
{
retVal += e * std::pow(10.0, 1.0 * i++);
}
i = 1;
for (const auto& e : decDeq)
{
retVal += e * std::pow(10.0, (-1.0) * i++);
}
return retVal;
}
测试代码如下:
int nLen = GetStringLength("a345阖家欢乐fF;$%^");
auto ff1 = StringToDouble(".12");
auto ff2 = StringToDouble("12.345");
auto ff3 = StringToDouble("123.45g.67Y");
auto ss1 = DoubleToString(12.345);
auto ss2 = DoubleToString(-16.10001);
cout << nLen << '\t' << ff1 << '\t' << ff2 << '\t'
<< ff3 << '\t' << ss1 << '\t' << ss2 << endl;
运行结果如下:
18 0.12 12.345 123.457 12.345000000000000