1

Let's say I have a double d = 123456789 (I know that the double is always representing an integer). I am trying to print it using C++ so that exactly 123456789 is printed. Unfortunately, this is not the default behavior:

double d = 123456789;
cout << d << "\n";

output: 1.23457e+08

I discovered the following trick/cheat:

double d = 123456789;
cout << (long) d << "\n";

output: 123456789

Is this the way to do it, or is there a cleaner way using some output manipulators?

karlosss
  • 2,816
  • 7
  • 26
  • 42
  • 3
    https://en.cppreference.com/w/cpp/io/manip – Jesper Juhl Jan 18 '20 at 15:46
  • 3
    Does this answer your question? [How to make C++ cout not use scientific notation](https://stackoverflow.com/questions/5212018/how-to-make-c-cout-not-use-scientific-notation) – lukehod Jan 18 '20 at 16:11
  • 1
    TL;DR potential dupe: `std::cout << std::fixed << std::setprecision(0) << d;`. – Evg Jan 18 '20 at 16:21

3 Answers3

3

std::setprecision can be used here.

#include <iomanip>   // std::setprecision
#include <iostream>  // std::cout

int main() {
  double d = 123456789;
  std::cout << std::setprecision(5) << d << "\n";
  // 1.2346e+08
  std::cout << std::setprecision(15) << d << "\n";
  // 123456789
}

The maximum precision can be set with

std::setprecision(std::numeric_limits<long double>::digits10 + 1)
Zheng Qu
  • 781
  • 6
  • 22
1

Edit: I'll leave this here for the info about casting, but the right way is to use setprecision as suggested in the other answers.

Casting to long is fine as long as your values can fit in a long. You can upgrade to long long or unsigned long long if you are dealing with values larger than can be represented by long. (use the signed version to support negative values).

Keep in mind that double/float can represent very large values so eventually you might encounter values that don't fit even in unsigned long long.

You can check for overflow with something like

if (d <= (double)std::numeric_limits<long long>::max()
     && d >= (double)std::numeric_limits<long long>::min())
{
    cout << (unsigned long long) d;
}
else
{
    cout << "value d is very large: " << d;
}
OLP
  • 803
  • 8
  • 10
1

You can use manipulator and set the output format as shown below

double d = 123456789;
std::cout << std::setprecision(9) << std::noshowpoint;
std::cout << d << std::endl;
Nagappa
  • 194
  • 2
  • 13