将 double 转换为具有固定宽度的 String [英] Convert double to String with fixed width

查看:25
本文介绍了将 double 转换为具有固定宽度的 String的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想将 double 转换为具有固定宽度的字符串.

如果宽度是 10,那么我希望 double 值四舍五入到这个宽度.

例如,如果 value = 102.121323435345 并且宽度为 10,那么这个值应该是,

<前>位置==> 0123456789值 = 102.121323

我可以使用 snprintf 来实现这一点,但我正在寻找一个 C++ 本机代码来做同样的事情.

<预><代码>字符缓冲区[125];snprint(buf, width, "%.6f", value);

我尝试使用下面的,但它对我没有多大帮助,

 <代码>std::ostringstream oss;oss << std::fixed << std::setw(10) << std::precision(6) << value;

std::setw 保证值的最小宽度,如果值大于宽度大小,则不会对值进行四舍五入.

谢谢.

解决方案

您可以使用 osteram::widthostream::precision 功能来实现您的目标,例如这个

std::ostringstream out;out.width(10);out.precision(10);出<<123.12345678910111213;

虽然它不会在点后添加零以尊重宽度,但它会在数字前添加空格(或您选择的任何字符).因此,如果您将 102 作为输入值传递,您将得到 '102' 或 '0000000102'(如果您调用 out.fill('0');)而不是 '102.000000'.

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.

解决方案

You can use osteram::width and ostream::precision function to achieve your goal, like this

std::ostringstream out;
out.width(10);
out.precision(10);
out << 123.12345678910111213;

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.

这篇关于将 double 转换为具有固定宽度的 String的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆