-1

I need to do this (does not round, floor or ceil):

example:

1.58700023 (16bits)

expected 1.58700000

i am doing this operation: (value-32768.0)/32768 to convert to (byte value to real value in float) int his conversion have this error = X.00000023 or others

2 Answers2

1

It's quite possible that you cannot do this with floats; note that not all values are exactly representable as a float: it's limited to 32 (typically) bits after all.

For printing, you should be able to use:

printf("%.3f", 1.58700023);

This will print 1.587 by rounding as the value is converted to string.

unwind
  • 391,730
  • 64
  • 469
  • 606
0

I assume you want to implement rounding with primitives.

To round to four decimal places, multiply with 10e4, convert to integer (effectively truncating or removing the decimals), then divide by float value 10e4 which converts the result back to float again. For example:

#include <stdio.h>

int main()
{
  double f = 1.58700023;
  printf("%10.10f\n", f);

  // Round to 4 decimal places
  double r = (int)(f*10000.0)/10000.0;
  printf("%10.10f\n", r);

  return 0;
}

This outputs:

1.5870002300
1.5870000000

There are many edge cases not supported by this routine, though. E.g., you may want to add one half of 1/10e4 to perform rounding to nearest next digit, etc.

csl
  • 10,937
  • 5
  • 57
  • 89