How to round a float?

Thread Starter

urb-nurd

Joined Jul 9, 2014
269
Hey guys, i am trying to round a float to one or two decimal places in MikroC but i am struggling.

I understand the floor and ceiling functions, but these appear to round to the nearest integer as opposed to decimal places.

This is likely a common question, but i have yet to find a decent answer (that i understood).
 

ErnieM

Joined Apr 24, 2011
8,377
If all you have is an integer rounding function you can multiply the number by 10 or 100, round it, then divide that by 10 or 100 to accomplish the desired rounding.
 

Thread Starter

urb-nurd

Joined Jul 9, 2014
269
That is what i have done for the time being.
I am incrementing all my variables by 0.1 and displaying them X10 : so 9.4 = 94 on screen.
 

ErnieM

Joined Apr 24, 2011
8,377
Why use a float at all to represent something like 9.4? If you adjust the units you are working in then the decimal portion goes away.

Example: 9.4 volts is also 9400 millivolts.

And you're not limited to the traditional engineering powers either: you can have a units such as 10*Volts or 100*Volts too.

Typically to put a number onto as display you first convert it to an ASCII string.

Strings are simple, each byte is a digit and you can count digits to insert the decimal place anywhere you wish it to be.

It's also pretty simple to strip out any leading or training zeros
 
Top