Reputation: 1644
I know how to limit the decimal and integer while printing values in printf (%x.x ), In my scenario I want to implement that while reading from the console itslef.
So is there any way to llimit the number of decimals in a floating point value while reading using scanf function?
I tried below , doesn't show any errors while compiling but get's the value 0 always
float f1;
.
.
scanf("%.3f",&f1);
printf("%3.3f\n",f1);
Upvotes: 0
Views: 2970
Reputation: 1765
If you check the documentation, it says
A format specifier for scanf follows this prototype:
%[*][width][length]specifier
and compare it to printf:
A format specifier follows this prototype:
%[flags][width][.precision][length]specifier
You will see, there is no precision
field in scanf. So i guess rounding (or casting to int to cut the digits) is the only way.
Upvotes: 4
Reputation: 6572
f1 = round( f1 * 1000.0 ) / 1000.0
. scanf
cannot help. BTW, use double
instead of float
.
Upvotes: 0