c - One digit after the decimal point in input -
this question has answer here:
- rounding number 2 decimal places in c 15 answers
how can take floating point number 1 digit after decimal point (0.1) using scanf in c language ? example user may type 3.25405... in variable 3.2 saved . how can ? different rounding floating point number .
read using fgets()
, post-process buffer. @devsolar
char buf[100]; if (fgets(buf, sizeof buf, stdin) == null) handle_eof(); char *p = strchr(buf,'.'); if (p && isdigit(p[1])) p[2] = 0; char *endptr; double y = strtod(buf, &endptr); ...
even better alert user of ignored additional input.
if (p && isdigit(p[1])) { if (p[2] && p[2] != '\n') puts("extra input ignored."); p[2] = 0; } char *endptr; double y = strtod(buf, &endptr);
Comments
Post a Comment