简体   繁体   English

C++ 中的浮点格式

[英]Float formatting in C++

How do you format a float in C++ to output to two decimal places rounded up?如何在 C++ 中格式化浮点数以输出到四舍五入的两位小数? I'm having no luck with setw and setprecision as my compiler just tells me they are not defined .我对setwsetprecision不走运,因为我的编译器只是告诉我它们not defined

cout << "Total : " << setw(2) << total << endl;

total outputs: Total : 12.3961总产出: Total : 12.3961

I'd like it to be: 12.40 or 12.39 if it's too much work to round up.我希望它是: 12.4012.39如果它的工作太多而无法汇总。

You need to include <iomanip> and provide namespace scope to setw and setprecision您需要包含<iomanip>并为setw and setprecision提供命名空间范围

#include <iomanip>
std::setw(2)
std::setprecision(5)

try:尝试:

cout.precision(5);
cout << "Total : " << setw(4)   << floor(total*100)/100 << endl;

or要么

 cout << "Total : " << setw(4)   << ceil(total*10)/10 << endl;

iostream provides precision function, but to use setw, you may need to include extra header file. iostream 提供了精度函数,但是要使用 setw,您可能需要包含额外的头文件。

Use cout << fixed or cout.setf(ios::fixed) , and std::cout.precision(<# of decimal digits>) as in the following (using the Clang-503.0.40 compiler included with OSX Mavericks):使用cout << fixedcout.setf(ios::fixed)std::cout.precision(<# of decimal digits>)如下(使用 OSX Mavericks 附带的 Clang-503.0.40 编译器):

#include <iostream>

int main()
{
   using namespace std;

   float loge = 2.718;
   double fake = 1234567.818;
   cout << fixed;
   cout.precision(2);
   cout << "loge(2) = " << loge << endl;
   cout << "fake(2) = " << fake << endl;
   cout.precision(3);
   cout << "loge(3) = " << loge << endl;
   cout << "fake(3) = " << fake << endl;
}

The output from this is (note the rounding):这个输出是(注意四舍五入):

loge(2) = 2.72
fake(2) = 1234567.82
loge(3) = 2.718
fake(3) = 1234567.818

This is the simple version.这是简单的版本。 In lieu of using cout << fixed;代替使用cout << fixed; , you can use cout.setf(ios::fixed); ,你可以使用cout.setf(ios::fixed); (for displaying scientific notation, replace fixed with scientific ; both will set the number of digits to the right of the decimal point). (为了显示科学记数法,用科学代替fixed ;两者都将设置小数点右侧的位数)。 Note the cout.precision() is also used to set the number of digits displayed in total on either side of the decimal point if the format flags do not include fixed or scientific .注意cout.precision()也被用来设定的,如果格式标志不包括固定科学上小数点的任一侧显示在总位数。 There are tutorials for this on the Internet.网上有这方面的教程。

To also include the trailing zero, it isn't sufficient to set the precision.要还包括尾随零,设置精度是不够的。 You also have to change the floating point format to fixed format, which uses the number of digits as told by setprecision as the number of digits after the decimal point :您还必须将浮点格式更改为固定格式,它使用setprecision告诉的位数作为小数点后的位数

std::cout << std::fixed << std::setprecision(2) << v;

Working online example code在线工作示例代码

If you want the trailing zero from rounding, you can use the C function printf .如果您想要四舍五入的尾随零,您可以使用 C 函数printf

#include <iostream>
#include <cstdio>

int main() {
    float v = 12.3961;
    std::printf("%.2f",v); //prints 12.40
}

Compared to:相比:

#include <iostream>
#include <iomanip>

int main() {
    float v = 12.3961;
    std::cout << std::setprecision(4) << v; //prints 12.4
}

You can do it with C++20 std::format :你可以用 C++20 std::format做到这一点:

std::cout << std::format("Total     : {:.2f}\n", total);

or the fmt::format function from the {fmt} library , std::format is based on.{fmt} 库中fmt::format函数, std::format基于。 {fmt} also provides the print function that integrates formatting and output making it even easier and more efficient ( godbolt ): {fmt} 还提供了集成格式化和输出的print功能,使其更容易、更高效( Godbolt ):

#include <fmt/core.h>

int main() {
  fmt::print("Total     : {:.2f}\n", 12.3961);
}

Output:输出:

Total     : 12.40

This uses the IEEE754 default rounding mode (round to nearest even) so you'll have to round up yourself ( How do I round up/down a decimal place of a float value? C++ ).这使用 IEEE754 默认舍入模式(舍入到最接近的偶数),因此您必须自己舍入(如何向上/向下舍入浮点值的小数位?C++ )。

This is a little dirty...这有点脏...

template <typename T>
string sFormat(const char *f, T value)
{
    char buffer[64];
    snprintf(buffer, sizeof(buffer), f, value);
    return string(buffer);
}

And do things like this :并做这样的事情:

cout << "Result :" << sFormat(" %5.2f", 3.14) << sFormat(" %5d", 2300) << endl;

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM