std::fixed, std::scientific, std::hexfloat, std::defaultfloat in C++
Last Updated :
06 Jul, 2017
Formatting in the standard C++ libraries is done through the use of manipulators, special variables or objects that are placed on the output stream. There are two types of floating point manipulators namely, fixed floating point and scientific floating point. These all are defined in header <iostream>.
Use of precision : In the default floating-point notation, the precision field specifies the maximum number of meaningful digits to display both before and after the decimal point, while in both the fixed and scientific notations, the precision field specifies exactly how many digits to display after the decimal point, even if they are trailing decimal zeros.
- std::fixed – Fixed Floating-point notation : It write floating-point values in fixed-point notation. The value is represented with exactly as many digits in the decimal part as specified by the precision field (precision) and with no exponent part.
- std::scientific – Scientific floating-point notation : It writes floating-point values in Scientific-point notation. The value is represented always with only one digit before the decimal point, followed by the decimal point and as many decimal digits as the precision field (precision). Finally, this notation always includes an exponential part consisting on the letter “e” followed by an optional sign and three exponential digits.
- std::hexfloat – Hexfloat floating-point notation : It outputs the desired number after the conversion into hexadecimal format after the precision of no. is initialized ( as discussed in prev. cases ).
- std::defaultfloat – defaultfloat floating-point notation : It outputs the desired number same as default after the precision of no. is initialized ( as discussed in prev. cases ). It is mainly used to distinguish among other used formats for understandability of code.
#include <iostream>
using namespace std;
int main()
{
double a = 4.223234232;
double b = 2323.0;
cout.precision(4);
cout << "Normal values of floating point numbers\na = " ;
cout << a << "\nb = " << b << '\n' ;
cout << "Values using fixed \n" << std::fixed;
cout << a << "\n" << b << '\n' ;
cout << "Values using scientific are : " << std::scientific << endl;
cout << a << '\n' << b << '\n' ;
cout << "Values using hexfloat are : " << std::hexfloat << endl;
cout << a << '\n' << b << '\n' ;
cout << "Values using defaultfloat are : " << std::defaultfloat << endl;
cout << a << '\n' << b << '\n' ;
return 0;
}
|
Output:
Normal values of floating point numbers
a = 4.223
b = 2323
Values using fixed
4.2232
2323.0000
Values using scientific are :
4.2232e+00
2.3230e+03
Values using hexfloat are :
0x1.0e49783b72695p+2
0x1.226p+11
Values using defaultfloat are :
4.223
2323
Like Article
Suggest improvement
Share your thoughts in the comments
Please Login to comment...