We are running a survey to help us improve the experience for all of our members. If you see the survey appear, please take the time to tell us about your experience if you can.
hi there please here is the sample prog. code
#include stdio.h #include conio.h void main() { clrscr(); float x=98.2344; printf("%2.2f",x); getch(); }
so output of this prog. is 98.23
upto here all thing's are ok but it is possible to move or assing the float value with limited number after decimal point; for example in above prog if we are taking the new float variable new_x and moving the x to new_x i.e. if x =98.2344 and i want to assign new_x = 98.23 or 98.2 or 98.234
Without knowing your floating point library, I can't give you a C code that will work for your system.
Some libs have rounding and truncation functions, like mfp_trunc() or fp_round(), that allow you to reduce the precision of the fp number to some decimal place, but the majority of uC fplibs don't. HOWEVER, these functions may not guarantee exact decimal chopping of the number, because of the inherent binary approximation.
An 'adequate' approach that is independent from fp library rounding functions could be:
/////////////////////////////////////////////////// // return a float truncated to a specified decimal // precision. // // ENTRY: // number float number to truncate // precision desired decimal precision, in // a power of 10, i.e., for 2 decimal // places use precision = 100, for 3 // decimals use 1000. // RETURNS: // float number truncated /////////////////////////////////////////////////// float fp_round(float number, unsigned int precision) { return((float) (((long) (number * (float) precision))/(float) precision)); } int main(void) { float f1, f2, f3; f1 = 3.141592653589793; // makes f1=3.141593 // the do{}while is to avoid compiler optimize-out do { f2 = fp_round(f1, 1000); // f2 = 3.141 f3 = fp_round(f1, 10); // f3 = 3.1 } while (f2 < f3); }
The above code compiles in about any compiler. It uses integer type castings, so it does not requires any special fplib code. This is just exampleware to illustrate my point, you can certainly optimize the concept.
You can, of course, use double instead of foat, and you can also implement it as a macro or inline function.
This approach may be slower than specific round() or trunc() functions, but it is lib-independent, and probably smaller than lib-specific functions.