Round off float values to fewr decimal places

Beta Testing discussion on mikroC PRO for PIC.
Post Reply
Author
Message
m.naveed
Posts: 10
Joined: 14 Nov 2013 06:07

Round off float values to fewr decimal places

#1 Post by m.naveed » 21 Dec 2015 04:17

Hello everyone!
I am working project which involves float point values. PWM duty is needed to set at a particular value where to float values (calculated from ADC) are equal.
Now the problem is that PWM duty doesn't stop any where it just scrolls 0-100-0, I think it is because it is difficult for float values to match exactly so I want to reduce them up to 3 or 4 decimal places (e.g. 2.9478578348.. to 2.948).
I have googled for "round off float values in mikroc" etc. but all the results I found were for displaying values not for using in other calculations and want I have to use the values for further calculation so I'm posting here a new thread.
Thanks to all in advance for any suggestions.

janni
Posts: 5373
Joined: 18 Feb 2006 13:17
Contact:

Re: Round off float values to fewr decimal places

#2 Post by janni » 22 Dec 2015 03:08

It's not possible to 'round-off' floating-point numbers internally stored in binary format, like that used in mC, with decimal places precision. Note that some decimal numbers cannot even be precisely stored in this format.

Added: As for the solution of your problem, why don't you convert the f-p numbers to integers multiplied by required power of 10? Integers equality can be checked without precision problems.

paulfjujo
Posts: 1544
Joined: 24 Jun 2007 19:27
Location: 01800 St Maurice de Gourdans France
Contact:

Re: Round off float values to fewr decimal places

#3 Post by paulfjujo » 25 Jun 2017 19:20

hello,


a bit "heavy" as solution , but if you have enough RAM,ROM ressources..

Code: Select all

 
unsigned char TEXTE[32];
unsigned char *txt;


txt=TEXTE;
 F1=  2.9478578348;
 Float2Ascii (F1,txt,3);
 F2=atof(txt);

F2= rounded value of F1 after 3 decimal digits
result:
watch.JPG

Post Reply

Return to “mikroC PRO for PIC Beta Testing”