将 double 转换为固定宽度的 String
我想将双精度数转换为固定宽度的字符串。
如果宽度是 10,那么我希望 double 值四舍五入到这个宽度。
例如,如果 value = 102.121323435345 并且宽度为 10,那么这个值应该是,
position==> 0123456789 value = 102.121323
我可以使用 snprintf 实现此目的,但我正在寻找 c++ 本机代码来执行相同的操作。
char buf[125];
snprint(buf, width, "%.6f", value);
我尝试使用下面的内容,但它对我没有多大帮助,
std::ostringstream oss;
oss << std::fixed << std::setw(10) << std::precision(6) << value;
std::setw 保证该值的最小宽度,如果该值大于宽度大小,它不会对值进行四舍五入。
谢谢。
I want to convert a double to string with fixed width.
If the width is 10, then I want the double value to get round off to this width.
For example, if value = 102.121323435345 and width is 10, then this value should be,
position==> 0123456789 value = 102.121323
I can achieve this with snprintf, but I am looking for a c++ native code to do the same.
char buf[125];
snprint(buf, width, "%.6f", value);
I tried to use the below, but it does not help me much,
std::ostringstream oss;
oss << std::fixed << std::setw(10) << std::precision(6) << value;
std::setw guarantiees the minimum width for the value and if the value is more than the width size, it does not round off the values.
Thanks.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
您可以使用 osteram::width 和 ostream:: precision 函数来实现你的目标,就像这样
虽然它不会在点后面添加零以尊重宽度但是它会在数字前添加空格(或您选择的任何字符)。因此,如果您传递 102 作为输入值,您将得到“102”或“0000000102”(如果您调用 out.fill('0');),而不是“102.000000”。
You can use osteram::width and ostream::precision function to achieve your goal, like this
Although it won't add zeros after the point in order to respect width but it will add spaces (or any character of you choise) before the number. So You'll get ' 102' or '0000000102' (if you call out.fill('0');) instead of '102.000000' if you pass 102 as a input value.
词汇转换怎么样?
这不完全是你所要求的。我只是想跳出框框思考。
您可能还想查看此问题以讨论有关格式设置的讨论 C 和 C++ 之间的差异并查看 Boost 格式库
How about lexical cast?
Its not exactly what you asked for. I was just trying to think outside the box.
You may also want to look at this question for a discussion on formatting differences between C and C++ and check out the Boost Format Library
这就是你想要的吗?在这里,我们计算可用精度并相应地设置 ostream。
顺便说一句,如果您想要大量计算数字的方法,具体方法如下。
Is that what you want? Here, we calculate the amount of available precision and set ostream accordingly.
Btw, if you want a truckload of ways to compute digits, here's how.