How to set precision of a float

68,572

Solution 1

You can't do that, since precision is determined by the data type (i.e. float or double or long double). If you want to round it for printing purposes, you can use the proper format specifiers in printf(), i.e. printf("%0.3f\n", 0.666666666).

Solution 2

You can't. Precision depends entirely on the data type. You've got float and double and that's it.

Solution 3

Floats have a static, fixed precision. You can't change it. What you can sometimes do, is round the number.

See this page, and consider to scale yourself by powers of 10. Note that not all numbers are exactly representable as floats, either.

Solution 4

It might be roughly the following steps:

  1. Add 0.666666666 with 0.0005 (we get 0.667166666)
  2. Multiply by 1000 (we get 667.166666)
  3. Shift the number to an int (we get 667)
  4. Shift it back to float (we get 667.0)
  5. Divide by 1000 (we get 0.667)

Thank you.

Solution 5

Most systems follow IEEE-754 floating point standard which defines several floating point types.

On these systems, usually float is the IEEE-754 binary32 single precision type: it has 24-bit of precision. double is the binary64 double precision type; it has 53-bit of precision. The precision in bit numbers is defined by the IEEE-754 standard and cannot be changed.

When you print values of floating point types using functions of the fprintf family (e.g., printf), the precision is defined as the maximum number of significant digits and is by default set to 6 digits. You can change the default precision with a . followed by a decimal number in the conversion specification. For example:

printf("%.10f\n", 4.0 * atan(1.0));  // prints 3.1415926536

whereas

printf("%f\n", 4.0 * atan(1.0));     // prints 3.141593
Share:
68,572
Zat42
Author by

Zat42

Dev @ kalvad.com

Updated on July 09, 2022

Comments

  • Zat42
    Zat42 almost 2 years

    Can someone explain me how to choose the precision of a float with a C function?

    Examples:

    theFatFunction(0.666666666, 3) returns 0.667

    theFatFunction(0.111111111, 3) returns 0.111

  • MK.
    MK. about 12 years
    you can do floor(x*100)/100.0