Mayank Jain
Mayank Jain

Reputation: 2564

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 (i.e. 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?

Upvotes: 3

Views: 418

Answers (3)

Nikos C.
Nikos C.

Reputation: 51920

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.

Upvotes: 1

xiaoy
xiaoy

Reputation: 41

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;
}

Upvotes: 0

Will Ness
Will Ness

Reputation: 71119

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;
}

Upvotes: 5

Related Questions