设置precision和剪辑尾随零,但是从不打印指数 [英] Set Precision and Clip Trailing Zeros but Never Print Exponent

查看:153
本文介绍了设置precision和剪辑尾随零,但是从不打印指数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要:


  1. 设置precision使花车四舍五入到百位(0.111版画0.11)

  2. 夹尾随零(1.0打印为1)

  3. 从不打印指数(1000.1打印为1000.1)

的printf(%.2f \\ n,输入); //处理1和3而不是2 结果
的printf(%0.2克\\ n,输入); //处理1和2,但不是3 结果
COUT<<集precision(2)LT;<输入<< ENDL; //处理1和2,但不是3

有一个的printf COUT 选项,可以让我处理所有这些?

Is there a printf or cout option that will let me handle all of these?

推荐答案

可悲的是,没有办法强迫流使用的的printf % ˚F行为。因此处理这个问题的唯一方法是手动微调必要小数。我补充说,处理这种一个C ++ code样品:<​​/ P>

Sadly there is no way to force streams to use printf's %f behavior. So the only way to handle this is trimming decimal places manually as necessary. I've added a C++ code sample that handles this:

string fullfloat( int( log10( numeric_limits< float >::max() ) ) + 5, '\0' ); // Adding 1 for the 10s place, 1 for the '.' 2 for the decimal places, and 1 for the null
const size_t size = fullfloat.size() - sprintf( &*fullfloat.begin(), "%.2f", input );

*( --mismatch( fullfloat.rbegin() + size, fullfloat.rbegin() + ( 3 + size ), "00." ).first ) = '\0';

fullfloat 现在将包含正确的字符串,而是因为它的规模将扩充到应用'\\ 0'性格得到它的打印性能是使用的唯一途径 c_str()

fullfloat will now contain the correct string, but because it's size will extend past the applied '\0' character the only way to get it to print property would be to use c_str():

cout << fullfloat.c_str();

这篇关于设置precision和剪辑尾随零,但是从不打印指数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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