I have a program that returns float numbers.I need to return the answer with exactly two digits after the decimal place and truncate any extra digits rather than rounding. Can someone give me an example please?
Asked
Active
Viewed 1,535 times
0
-
In C, when you convert a floating-point number to an int, the fractional part is discarded. So to truncate to two places past the decimal, you can multiply by 100, convert to int, and divide by 100. (But see the next comment.) – Steve Summit Nov 19 '16 at 17:18
-
2Beware that under the vast majority of today's computers, there's no such thing as a number that has exactly two (decimal) fractional digits past the decimal point. Even if you think you've converted to exactly, say, 1.23, internally it's probably 1.2299999 or 1.23000001. So you'll probably have to round these numbers on printout anyway, for example with `printf %.2f`. – Steve Summit Nov 19 '16 at 17:19
1 Answers
2
There is a special function for truncation: trunc(..)
which discards everything after a decimal point.
If you want to truncate after a certain number of decimal digits, you can do something like following:
trunc(number * 100) / 100
It should be obvious how above line works.

HolyBlackCat
- 78,603
- 9
- 131
- 207
-
-
This approach is OK for many situations. It does have trouble with cases outside typical OP concerns: 1) values that are near a multiple of 1/100 as the `number * 100` introduces an additional rounding. 2) Overflow with `|number| > DBL_MAX/100`. 3) special values like `-0.0, INF`. – chux - Reinstate Monica Nov 19 '16 at 19:44
-
-
The main issue of "`number * 100` introduces an additional rounding." seems to be only solvable by using extended precision in some fashion. I see no use case for a "truncated rounded to 2 digits" vs. "rounded" like [here](http://stackoverflow.com/a/25110157/2410359). Knowing OP's use case would help. I see a robust answer as a challenging problem. The `|number| > DBL_MAX/100` is easy to solved with a compare or `int dummy; if (modf(number, &dummy) == 0) return number;` to not bother with whole numbers. – chux - Reinstate Monica Nov 19 '16 at 19:57