开发者

How to output a float neither in scientific, nor in fixed point notation in std::cout?

#include <iostream>

int main()
{
    float test = 12535104400;

    std::cout << test;

    std::cin.get();
    return 0;
}

//on msvc 2010 this ouputs:  1.25351e+0开发者_如何学编程10

I would like it to output just "12535104400" or in other words, the human readable format which has no leading zeros, but outputs the full value of a number.


The particular number cannot be accurately represented, for example try the following:

  float v = 12535104400;
  cout.precision(0);
  cout << fixed << v << endl;

You'll see it outputs: 12535104512


You will need to include <iomanip> :

int main()
{
    const double test = 12535104400;

    std::cout << std::fixed << std::setprecision(0) << test;

    std::cin.get();
    return 0;
}
  • std::fixed is the manipulator which uses fixed-point precision (not scientific notation)
  • std::setprecision(0) sets how many digits to display after the decimal point


float test = 12535104400;

This should be a compiler error if your compiler doesn't support long long and int is 32-bit. Use floating literals instead of integer literals e.g 1234.0f vs 1234

#include <iostream>
#include <iomanip>
int main()
{
    float test = 12535104400.0f;

    std::cout << std::setiosflags(ios::fixed) << std::setprecision(0) << test;

    std::cin.get();
    return 0;
}

should print what you want. But beware that float isn't that precise


You are out of luck, 4-byte float can store cca 7 digits. Use double or long for such numbers.


In order to format the output in iostream, you'll need manipulators


If you're willing to lose precision, you can typecast it to an integer.

cout << int(test);

or

cout << (int)test;

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜