首页 > 解决方案 > cout 浮动,没有尾随零,并且后面只有 3 位数字

问题描述

我正在尝试打印一个float变量,我希望它只有 3 位数字。但是,如果它们为零,则它们最终不会打印。

例如

1.230 -> should be out like this 1.23
1.456432 -> 1.456
1.4000006 -> 1.4

目前我正在使用

cout<<fixed<<setprecision(3) <<res2<<endl;

它仍然显示更多的零,例如 0.010 但它应该是 0.01

标签: c++

解决方案


一种方法是使用手动将其解析为字符串stringstream并删除尾随零。string::find_last_not_of编辑:正如@Eljay 指出的那样,find_last_not_of不适用于1010or之类的情况120。相反,以下代码只是不断删除最后一个0.如果存在浮点。

#include "iostream"
#include "iomanip"
#include "vector"

using std::cout;
using std::string;
using std::setprecision;
using std::fixed;
using std::stringstream;
using std::vector;

string removeTrailingZeros(float number) {
  stringstream stream;
  stream << fixed << setprecision(3) << number;
  string floatStr = stream.str();
  while (floatStr.find('.') != string::npos && floatStr.back() == '0' || floatStr.back() == '.')
    floatStr.pop_back();
  return floatStr;
}

int main() {
  vector<float> numbers = {
    1010,   
    120, 
    1.50005, 
    0.004, 
    1.9994, 
    1.9996,
    2.4321, 
    0,   
    -1.5,    
    0.69,  
    0.1,
    1.007
  };
  for (auto n : numbers) {
    cout << fixed << setprecision(3) << n << ": " << removeTrailingZeros(n) << '\n';
  }
  return 0;
}

输出:

1010.000: 1010
120.000: 120
1.500: 1.5
0.004: 0.004
1.999: 1.999
2.000: 2
2.432: 2.432
0.000: 0
-1.500: -1.5
0.690: 0.69
0.100: 0.1
1.007: 1.007

推荐阅读