If I have a float number- 28.274309, and I want to show only 1 digit after the dot, I use %.1f. But then the result is 28.3. How do I make it 28.2 and not 28.3?
Asked
Active
Viewed 62 times
0
-
Why do you want 28.2 when 28.3 is closer to the true value? – chux - Reinstate Monica Dec 05 '17 at 17:05
-
Because its for an assignment i do and they asked for 28.2... weird, but how do i do it correctly? – linoiushi Dec 05 '17 at 17:09
-
`trunc(x*10.0)/10.0;` [ref](https://stackoverflow.com/a/12764022/2410359) – chux - Reinstate Monica Dec 05 '17 at 17:11
-
2@chux: That does not work. For example, if `x` is 1.79999999999999982236431605997495353221893310546875, the desired result would be 1.7 in decimal, and nearly that in binary. But `x*10.0` produces exactly 18, `trunc(x*10.0)` produces 18, and `trunc(x*10.0)/10.0` produces 1.8000000000000000444089209850062616169452667236328125. – Eric Postpischil Dec 05 '17 at 17:44
-
@EricPostpischil Perhaps it may not work for a select case, yet `1.7999999999999998223...` is not a `float` value and OP's post is about `float`. I too am looking for a `float` counter example. `trunc(x*10.0)/10.0;` is taking advantage of the wider precision math of `double`. – chux - Reinstate Monica Dec 05 '17 at 17:52
-
@EricPostpischil Of course OP use of "float" could be taken as any _floating point_ type. My comment works `float`. - No counter example yet. – chux - Reinstate Monica Dec 05 '17 at 17:58
-
1@chux multiplying the conversion to `double` of a `float` by `10.0` is exact (they respectively use 24 and 3 bits of significand, so the product needs 27 to be represented), making the `trunc(x*10.0)` part of your method correct. I would compose the output from that integer to be on the safe side. – Pascal Cuoq Dec 06 '17 at 07:13