Home Ask Login Register

Developers Planet

Your answer is one click away!

Cnth February 2016

Input decimal numbers in C

I am extremely beginner in programming language. so i am facing some problems. please help me out. Is it possible to take input a floating or double number with 2 digits after the decimal point using 'scanf' in C ??

Thanks in advance.

Answers


Dubon February 2016

See here: How to only accept a certain precision (so many decimals places) in scanf?

float value;
scanf("%4f", &value);

It's not really do that, but reads 4 digit edit: 4 characters float number. You can set other number instead of 4.

If you really need only 2 decimal places you can read the number with scanf, and after that round it using roundf.

#include <math.h>
...
float value;
scanf("%f", &value);
value = roundf(value*100)/100


Spencer February 2016

You can read floats with

float a;
scanf("%f", &a);

You can read doubles with

double a;
scanf("%lf", &a);

Post Status

Asked in February 2016
Viewed 3,663 times
Voted 5
Answered 2 times

Search




Leave an answer


Quote of the day: live life