【问题标题】:Truncate float so as to have only two decimals [duplicate]截断浮点数以便只有两位小数[重复]
【发布时间】:2013-04-20 18:43:42
【问题描述】:

C++

我想coutfloat f = 2.3333,但只有两位小数。我怎么做? 我记得这样的事情,但它不起作用:

cout << f:2 << endl;

【问题讨论】:

  • 我不知道你是从哪里记住的!
  • @sftrabbit 我猜他是从printf() 或其他编程语言中记住的。

标签: c++ floating-point truncate rounding fractions


【解决方案1】:

使用流操作符fixedsetprecision

#include <iomanip>

float f = 2.3333;
std::cout << std::setprecision(2) << std::fixed << f;

【讨论】:

    【解决方案2】:

    我设法在没有 iomanip 的情况下解决了它:

    cout << (((int)f*100) % 100)/100; 
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2017-07-04
      • 2019-04-23
      • 2015-03-05
      • 2010-10-08
      • 2020-05-12
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多