PHPFixing
  • Privacy Policy
  • TOS
  • Ask Question
  • Contact Us
  • Home
  • PHP
  • Programming
  • SQL Injection
  • Web3.0

Wednesday, August 10, 2022

[FIXED] Why does std::cout print floats, doubles and long doubles to the same decimal precision?

 August 10, 2022     c++, cout, decimal, std, stringstream     No comments   

Issue

Intuitively I would think that long doubles have more decimal places than doubles and doubles have more decimal places than floats, however, if so why does std::cout print out floats, doubles, and long doubles at the same decimal precision, even when they have overloads for all primitive data types?

C++ source code:

#include <iostream>

#define PI 3.1415926535897932384626433832;

int main()
{
    float f = PI;
    double d = PI;
    long double ld = PI;

    std::cout << f << std::endl;
    std::cout << d << std::endl;
    std::cout << ld << std::endl;

    return 0;
}

output:

3.14159
3.14159
3.14159

Solution

Values have a fixed precision depending on the type and you can't change it. It's implementation defined. You can only change the precision of the output and there is just one setting for all types of floats. You can't have different output precision for float, double and long double. The default output precision for all types of float is 6.

It's technically not possible to set a different output precision for e.g. float than e.g. double.

There are no overloads for std::setprecision. Each std::basic_ostream can hold only one value for precision.



Answered By - Thomas Sablik
Answer Checked By - Willingham (PHPFixing Volunteer)
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg
Newer Post Older Post Home

0 Comments:

Post a Comment

Note: Only a member of this blog may post a comment.

Total Pageviews

Featured Post

Why Learn PHP Programming

Why Learn PHP Programming A widely-used open source scripting language PHP is one of the most popular programming languages in the world. It...

Subscribe To

Posts
Atom
Posts
Comments
Atom
Comments

Copyright © PHPFixing