Click here to Skip to main content
15,884,859 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
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.
Posted

 
Share this answer
 
You can remove the thousands separators from the string before passing it to strtod.

If you want to store the value as CURRENCY in the database you may also write your own parser using integers.

A possible solution (compiled but not fully tested):
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;
}
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900