简体   繁体   中英

Printing float with precision 2 but without decimal(.) in C++

Please Consider Code snippet shown below:

// setprecision example
#include <iostream>     // std::cout, std::fixed
#include <iomanip>      // std::setprecision

int main () {
  double f =3.14159;
  std::cout.precision(2);

  std::cout << f*100 << '\n';
  return 0;
}

What I want to do is print on screen 314 (ie print f without decimal with precision as 2)

I want thinking of first setting precision as 2 and then multiplying with 100.

But it seems that precision is finally applied on f*100. Can anyone suggest of any way to apply precision on f then to multiply the number by 100 and finally to print with precision 0?

Multiply by a 100 and print with precision 0.

int main () {
  double f =3.14159;
  std::cout.precision(0);

  std::cout << std::fixed << f*100 << '\n';
  return 0;
}

There's actually a "proper" way to do this, without having to alter the value at all. You can prepare an std::ostringstream that will do this for you by using your own std::numpunct subclass:

#include <locale>

class no_decimal_punct: public std::numpunct<char> {
protected:
    virtual char do_decimal_point() const
    { return '\0'; }
};

You can now prepare an std::ostringstream that will use the above no_decimal_punct class:

#include <sstream>
#include <iostream>

std::ostringstream strm;
strm.imbue(std::locale(strm.getloc(), new no_decimal_punct));
strm.precision(2);
std::fixed(strm);

double f = 3.14159;
strm << f;
std::cout << strm.str() << '\n';

The advantage here is that you're not changing the value of f , which could potentially print something else than intended due to FP errors.

There are many ways to display 314:

#include <iostream>
using namespace std;
int main() {
  const double PI = 3.1415926;
  cout.precision(3);
  cout<<PI * 100<<endl;
}

#include <iostream>
using namespace std;
int main() {
  const double PI = 3.1415926;
  cout<<(int)(PI * 100)<<endl;
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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