本文介绍了将带有千位(和十进制)分隔符的字符串转换为double的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
用户可以在文本框中输入 double
。数字可能包含数千个分隔符。我想在输入数字插入数据库之前验证用户输入。
是否有可以转换此类输入的C ++函数( 1,555.99
)加倍?如果有,如果输入无效,它是否会发出错误信号(我不希望最终得到类似 atof
的功能)?
像 [],但必须接受带有千位分隔符的输入。
User can enter double
into textbox. Number might contain thousands separators. I want to validate user input, before inserting entered number into database.
Is there a C++ function that can convert such input (1,555.99
) into double? If there is, can it signal error if input is invalid (I do not want to end up with function similar to atof
)?
Something like strtod[^], but must accept input with thousands separators.
推荐答案
bool StrToCy(CY& cy, char *p)
{
bool bNeg = false;
char *pStop;
cy.int64 = 0;
LONGLONG l1 = 0;
LONGLONG l2 = 0;
// Skip leading spaces
while (*p == ' ')
p++;
// Get optional sign
if (*p == '-')
{
bNeg = true;
p++;
}
else if (*p == '+')
p++;
// Get digits ignoring thousands separator
while (*p == ',' || isdigit(*p))
{
if (isdigit(*p))
l1 = l1 * 10LL + (*p - '0');
p++;
}
// Get trailing digits
if (*p == '.')
{
l2 = strtoul(++p, &pStop, 10);
int digits = (int)(pStop - p);
while (digits < 4)
{
l2 *= 10LL;
++digits;
}
}
else
pStop = p;
if (bNeg)
l1 = -l1;
if (*pStop <= ' ' && l1 < (LLONG_MAX / 10000LL) && l2 < 10000LL)
{
cy.int64 = l1 * 10000LL + l2;
return true;
}
return false;
}
这篇关于将带有千位(和十进制)分隔符的字符串转换为double的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!