c++ - Set the digits after decimal point -


i have float number example 12.12123 there function display number 2 digits after decimal point 12.12 ?

here code:

y1 = ( c1 - (a1 * x)) / b1;  y2 = ( c2 - a2 * x) / b2;  if (y1 == y2)   cout << "the same"; 

so if y1 = 1.001 , y2 = 1.002 not appear same.

i tried add. cout.setf(ios::fixed, ios::floatfield); cout.precision(2);

but not seem help.

/* c way */ #include <stdio.h> ... float f = 12.12123f; printf("%.2f",f);  // c++ way #include <iostream> ... float f = 12.12123f; std::cout.setf(std::ios_base::fixed, std::ios_base::floatfield); std::cout.precision(2); std::cout << f;  // alternative c++ way #include <iostream> #include <iomanip> ... float f = 12.12123f; std::cout << std::fixed << std::setprecision(2) << f; 

in c, 0 padding added automatically right if there not enough digits print. in c++ examples, instead, disabled; enable behavior, should enable fixed mode on stream std::fixed (or enabling relevant stream flags std::ios_base::setf()).

edit: remembered wrong; if fixed not set, precision setting says stream total number of digits display, including ones before decimal point. so, in case think way use fixed mode (examples fixed), yield same behavior of printf.


links:


Comments

Popular posts from this blog

cakephp - simple blog with croogo -

How to group boxplot outliers in gnuplot -

bash - Performing variable substitution in a string -