# How to round a float?

Discussion in 'Embedded Systems and Microcontrollers' started by urb-nurd, Mar 11, 2015.

1. ### urb-nurd Thread Starter Member

Jul 9, 2014
269
3
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).

2. ### ErnieM AAC Fanatic!

Apr 24, 2011
7,434
1,625
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.

3. ### urb-nurd Thread Starter Member

Jul 9, 2014
269
3
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.

4. ### ErnieM AAC Fanatic!

Apr 24, 2011
7,434
1,625
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

5. ### MrChips Moderator

Oct 2, 2009
12,623
3,451
When using MCU I stay away from floats as if they were infested with the plague.