【问题标题】:Control the Precision of float number in a string - C++控制字符串中浮点数的精度 - C++
【发布时间】:2016-09-29 14:55:16
【问题描述】:

我正在尝试控制我在 String 中添加的 Digits 的数量,但我无法控制它,因为我正在打印一个字符串数组。

float loads[n] = { 1,2,3,0.05,1,2,3,0.5,1,2,3,3,1,2 };
string print[nBits] = { "" };
int n=14;
int BB;
.
.
.
void main(){
 for (int j = 0; j < nBits; ++j)// 2^n
   {     
         for (int i = 0; i < n; ++i) // n
        {
            BB = arr[j][i];
            R = loads[i];
            if (BB == 1) {
            print[j]+="" +std::to_string(loads[i])+"//";
        }
   }
}

但我最终得到了一个看起来像这样的字符串数组:

0.050000//3.000000//...

在将浮点数添加到字符串之前,有什么方法可以控制它的精度吗?

(所以我可以让结果字符串控制固定数量的数字)

0.05//3.00// ...

【问题讨论】:

标签: c++ string floating-point precision


【解决方案1】:

std::stringstreamstd::fixedstd::setprecision(n) 一起使用。

http://en.cppreference.com/w/cpp/io/manip

【讨论】:

    【解决方案2】:

    您可以使用标准的流媒体机制:

    可以使用ostream来生成字符串:

    #include <ostream>
    #include <sstream>
    #include <iomanip>
    
    std::ostringstream stream;
    for(...) {
       stream << loads[i] << "//";
    }
    std::string str =  stream.str();
    

    这个想法是生成一个流,您也可以流式传输字符串。然后,您可以使用stream.str() 从中生成std::string。流具有如何转换数字的默认值。您可以使用std::setprecisionstd::fixed 以及其他变量来影响这一点(有关更多信息,请参阅C++ stdlib reference)。

    使用std::setprecisionstd::fixed

    std::ostringstream stream;
    // set the precision of the stream to 2 and say we want fixed decimals, not
    // scientific or other representations.
    stream << std::setprecision(2) << std::fixed;
    
    for(...) {
       stream << loads[i] << "//";
    }
    std::string str =  stream.str();
    

    你找到另一个例子here

    sprintf

    您始终可以采用 C 方式并使用 sprintf,但不鼓励这样做,因为您必须提供正确长度的缓冲区,例如:

    char buf[50];
    if (snprintf(buf, 50, "%.2f", loads[i]) > 0) {
       std::string s(buf);
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多