Search code examples
cscanf

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 ??


Solution

  • 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