Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to set precision of a float

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

like image 994
Zat42 Avatar asked Feb 09 '12 15:02

Zat42


People also ask

How do you set the precision of a float variable in C++?

You can't set precision of a float or double variable. Only for the input/output of such a variable. But you shouldn't be using float or double for monetary values to begin with, due to the fact that floating-point values/math is inprecise.

How precise can a float be?

A float has 23 bits of mantissa, and 2^23 is 8,388,608. 23 bits let you store all 6 digit numbers or lower, and most of the 7 digit numbers. This means that floating point numbers have between 6 and 7 digits of precision, regardless of exponent.


1 Answers

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).

like image 125
Dan Fego Avatar answered Sep 24 '22 22:09

Dan Fego