将带有千位(和十进制)分隔符的字符串转换为double [英] Convert string with thousands (and decimal) separator into double

查看:306
本文介绍了将带有千位(和十进制)分隔符的字符串转换为double的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

用户可以在文本框中输入 double 。数字可能包含数千个分隔符。我想在输入数字插入数据库之前验证用户输入。



是否有可以转换此类输入的C ++函数( 1,555.99 )加倍?如果有,如果输入无效,它是否会发出错误信号(我不希望最终得到类似 atof 的功能)?



strtod [ ^ ],但必须接受带有千位分隔符的输入。

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.

推荐答案

格式化货币的简单函数 [ ^ ]可能值得一试。
A Simple Function for Formatting Currency[^] might be worth a try.


您可以在将字符串传递给 strtod 之前从字符串中删除千位分隔符。



如果要在数据库中将值存储为 CURRENCY ,您也可以使用整数编写自己的解析器。



一个可能的解决方案(编译但未经过全面测试):

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;
}


这篇关于将带有千位(和十进制)分隔符的字符串转换为double的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆