标准库
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;
}
性能取舍