Raj*_*ian 15 c c++ type-conversion
我想将浮点值存储到字符串中而不会丢失或添加任何单个精度数字.
例如,如果我的浮点值是23.345466467,我想我的字符串有海峡="23.345466467"确切的数字.
我尝试使用%f的CString格式函数.它只给出了前6个精度.或者如果我使用%10,如果我的浮点值精度小于10,则会增加一些垃圾精度.我想在我的字符串中获得精确的浮点值.这该怎么做?
Hug*_*ues 10
请参阅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
Run Code Online (Sandbox Code Playgroud)
或者等效地,用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
Run Code Online (Sandbox Code Playgroud)
这取决于您的浮点值23.345466467是否可以准确表示(可能不是)
我也会质疑为什么你需要这样做?你打算用什么字符串表示?你知道双重和小数类型吗?
[ 未经测试:你可以尝试施法加倍然后使用"%d"也许这会拉出额外的"后卫"数字'但它仍然不适用于所有值]
Art*_*yom -3
首先:您无法将浮动转换为字符串并返回,而可能会损失一两个。因为这不是一对一的转换,因为它们使用不同的基数。
为了保持浮点类型的最佳精度:
std::string convert(float value)
{
std::stringstream ss;
ss << std::setprecision(std::numeric_limits<float>::digits10+1);
ss << value;
return ss.str();
}
Run Code Online (Sandbox Code Playgroud)
或者更通用的
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();
}
Run Code Online (Sandbox Code Playgroud)
它会切断您不需要的数字,但保持尽可能高的精度。