[英]How to convert double to string with precision for total number of digits(both left and right side of the decimal)?
I am looking for a way to convert double to string in c++ such that total number of digits remain to be 10 irrespective of how many are present before and after the decimal point and irrespective of the zeroes.我正在寻找一种在 c++ 中将双精度转换为字符串的方法,这样无论小数点前后有多少位和零位,总位数都保持为 10。 Examples for better understanding:
更好理解的例子:
0.00000000000000000000 =expected outcome> 0.0000000000 0.00000000000000000000 =预期结果> 0.0000000000
12345.00000000000000000 =expected outcome> 12345.00000 12345.00000000000000000 =预期结果> 12345.00000
-15.123456789012 =expected outcome> -15.12345678 -15.123456789012 =预期结果> -15.12345678
I couldnt find any relevant answer.我找不到任何相关的答案。 For the methods like snprintf, std::setprecision with ostringstream, to_string, Boost's lexical_cast, some of the above case fails.
对于 snprintf、std::setprecision 和 ostringstream、to_string、Boost 的 lexical_cast 等方法,上述某些情况会失败。
Example of code:代码示例:
double num = 12345.0000000000001;
std::ostringstream streamObj2;
streamObj2 << std::fixed << std::setprecision(10) << num;
std::string strObj2 = streamObj2.str();
std::cout << strObj2 << '\n';
The output = 12345.0000000000, which is not what I am expecting. output = 12345.0000000000,这不是我所期望的。 Removing std::fixed gives output as 12345
删除 std::fixed 给 output 为 12345
What I require = 12345.00000我需要的 = 12345.00000
Please help me, thanks.请帮助我,谢谢。
Thanks for the comments, because of which I found the answer.感谢您的评论,因此我找到了答案。 Using std::showpoint instead of std::fixed helped fulfill the requirement.
使用 std::showpoint 而不是 std::fixed 有助于满足要求。
double num = 12345.0000000000001;双数 = 12345.0000000000001;
std::ostringstream streamObj2; std::ostringstream 流Obj2;
streamObj2 << std::showpoint << std::setprecision(10) << num; streamObj2 << std::showpoint << std::setprecision(10) << num;
std::string strObj2 = streamObj2.str(); std::string strObj2 = streamObj2.str();
std::cout << strObj2 << '\n'; std::cout << strObj2 << '\n';
Output: 12345.00000 Output: 12345.00000
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.