# Rounding float number

I want to enable user to change the duration of PWM from 0 to 255, the number should be in minute and increase/decrease with two push buttons.

``````(X) x 255 / 60000 = minute
``````

In above example each time plus button pressed value (X) will multiple by the numbers of button pressed.

``````if (plusButton == HIGH) {
PWMduration += (X);
}
``````

The nearest number i found is 235.29 which equals to almost 1 minute:

``````235.29 x 255 / 60000 = 0.9999
``````

How can i round that number to 1? or is there any other alternative solution to calculate this?

• Use 235.294117647? Jun 25, 2019 at 11:50
• @Majenko equals `0.99999999999975` Jun 25, 2019 at 11:54
• In float terms that's 1. I don't think you can actually represent 1 in a float. Jun 25, 2019 at 11:55
• so what's the solution? can i convert it to int? Jun 25, 2019 at 11:57
• What you want to do is calculate the delay based on the number of minutes. Not change the delay depending on the number of button presses. Keep the minutes as an integer. Then use that integer to calculate how long each delay interval should be. Jun 25, 2019 at 12:12

You can cast it to an integer after adding an offset.

Casting to an int will lower the value to the lowest integer value (e.g. 0.9975 will become 0). However, if you want an accuracy of 0.5 (e.g. all values from 0.5 <= x < 1.5 should be 1.0), than add 0.5, thus:

``````int roundedValue = (int)(0.9975 + 0.5);
``````

If you use constants and want to calculate with it, either add .0 to it, or use a f(loat) or d(ouble) postfix, e.g.:

``````float f = 12.0 / 3.0;
``````

or

``````float f = 12f / 3f;
``````

Than calculate the rounded value:

``````int roundedValue = (int)(f + 0.5);
``````