c++ std::to_string doube或float去除小数点尾部的0

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/river472242652/article/details/85614824

标准库

std::to_string(double) 可以将一个float或者double转换成字符串,但是会直接变为.000000的格式(如果尾部为0).

这里使用正则匹配的方式去除尾部的0.(当然也可以使用boost的boost::lexical_caststd::string精确方式,但是会出现.99999999999999999999)
因此

static std::string doubleToString(double price) {
	auto res = std::to_string(price);
	const std::string format("$1");
	try {
		std::regex r("(\\d*)\\.0{6}|");
		std::regex r2("(\\d*\\.{1}0*[^0]+)0*");
		res = std::regex_replace(res, r2, format);
		res = std::regex_replace(res, r, format);
	}
	catch (const std::exception & e) {
		return res;
	}
	return res;
}

性能取舍
整数测试与性能小数测试与性能

猜你喜欢

转载自blog.csdn.net/river472242652/article/details/85614824
今日推荐