Qt/C++编程实现:数字转化成万,亿为单位显示

思路:首先先将数字转变成含指定位置小数点的字符串,然后根据小数点个数来决定数字转换后的单位(一个小数点代表单位为万,两个为亿,以此内推)
最后通过QString的方式四舍五入

注意头文件的引用

#include 
#include 
#include 
#include 	
class Num : public std::numpunct
{
protected:
	virtual char do_thousands_sep() const
	{
		return '.';
	}

	virtual std::string do_grouping() const
	{
		return "\04";
	}
};
int MainWidget::convertNum(QString & strNum, int num)
{
	std::locale loc(std::locale(), new Num());
	std::ostringstream oss;
	oss.imbue(loc);
	oss << num;
	std::string v = oss.str();
	int index = std::count(v.begin(), v.end(), '.');
	int a = v.find_first_of('.');
	if (index > 0) {
		std::string result = v.substr(0, a + 1 + 2);
		strNum = QString("%1").arg(QString::fromStdString(result).toDouble(), 0, 'g', a + 1);
	}
	else if (index == 0) {
		std::string result = v.substr(0, 4);
		strNum = QString::fromStdString(result);
	}
	return index;
}

第二种方法,不需要借用std

int  MainWidget::convertNum(QString & strNum, int num)
{
	QString strInfoNum = QString::number(num, '.', 0);
	int strLen = strInfoNum.length();
	int index = 0;
	while (strLen > 4)
	{
		strLen = strLen - 4;
		strInfoNum.insert(strLen, ".");
		index++;
	}
	if (index > 0) {
		int x = strInfoNum.indexOf(".");
		strInfoNum = strInfoNum.left(x + 3);
		strNum = QString("%1").arg(strInfoNum.toDouble(), 0, 'g', x + 1);
	}
	else if (index == 0) {
		strNum = strInfoNum;
	}
	return index;
}

你可能感兴趣的:(C/C++,Qt)