我想在不丢失或添加任何单精度数字的情况下将浮点值存储到字符串中。
例如,如果我的浮点值是23.345466467,我希望我的字符串具有str = "23.345466467“的精确数字。
我尝试使用带有%f的CString格式函数。它只给出了前6个精度。或者,如果我使用%10,如果我的浮点值的精度小于10,它会添加更多的垃圾精度。我想在我的字符串中获得精确的浮点值。该怎么做呢?
发布于 2010-12-16 19:12:45
第一:你不能在不丢失一些东西的情况下将浮点数转换成字符串,然后再转换回来。因为这不是一对一的转换,因为它们使用不同的基础。
为了保持浮点类型的最佳精度:
std::string convert(float value)
{
std::stringstream ss;
ss << std::setprecision(std::numeric_limits<float>::digits10+1);
ss << value;
return ss.str();
}或更通用的
template<typename FloatingPointType>
std::string convert(FloatingPointType value)
{
std::stringstream ss;
ss << std::setprecision(std::numeric_limits<FloatingPointType>::digits10+1);
ss << value;
return ss.str();
}它会去掉你不需要的数字,但尽可能保持最高的精度。
发布于 2014-05-03 05:43:41
请参阅http://randomascii.wordpress.com/2012/03/08/float-precisionfrom-zero-to-100-digits-2/中的详细讨论。
简而言之,最小精度如下所示:
printf("%1.8e", d); // Round-trippable float, always with an exponent
printf("%.9g", d); // Round-trippable float, shortest possible
printf("%1.16e", d); // Round-trippable double, always with an exponent
printf("%.17g", d); // Round-trippable double, shortest possible或者等效地,使用std::ostream& os
os << scientific << setprecision(8) << d; // float; always with an exponent
os << defaultfloat << setprecision(9) << d; // float; shortest possible
os << scientific << setprecision(16) << d; // double; always with an exponent
os << defaultfloat << setprecision(17) << d; // double; shortest possible发布于 2010-12-16 18:59:54
这将取决于浮点值23.345466467是否可精确表示(可能不是)
What Every Computer Scientist Should Know About Floating-Point Arithmetic
Why Floating-Point Numbers May Lose Precision
我还会问你为什么需要这样做?您将使用字符串表示法来做什么?你知道双精度和小数类型吗?
未测试的:您可以尝试强制转换为双精度,然后使用"%d“也许这会拉入额外的”防护“数字,但它仍然不适用于所有值
https://stackoverflow.com/questions/4459987
复制相似问题