'How to round a decimal number to the nearest thousandths in c
I want a c program to round a decimal number to the thousandths position (the third position to the right of the decimal point)
Solution 1:[1]
The main problem is that C does not support decimal numbers natively, only binary. So any time you deal with decimal numbers, you generally need to convert them to binary (on input) and then convert them back to decimal on ouput. C supports two kinds of binary numbers (binary integers and binary floating-point), so this leads to two ways of dealing with it
use binary integers (
intorlong). For decimal integers this is fine, but if you have decimal fractions, this works less well. You end up needing to pick a (generally fixed) denominator and work with all numbers as being implicitly multiplied by that. In your case you might have a fixed denominator of1000to get (always) 3 decimal places, but converting input and output is harduse binary floating point. The problem is that binary floating point cannot exactly represent decimal fractions, so you end up rounding things. As long as you are aware of this rounding (so you value may be off by some small epsilon value) this is ok, but you may be suprised, particularly if you convert the floating point values to binary integers, which truncates rather than rounding. Careful use of the
roundfunction can avoid problems here.
So how to handle your case? It depends on what you want to do. If you just want to read a decimal value then write it back out rounded to 3 places, that is easiest with floating point:
double val;
scanf("%f", &val); /* read a decimal value */
printf("%.3f", val); /* write it with 3 digits after the decimal (rounding to nearest) */
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Chris Dodd |
