Main Site Documentation

Rounding a number - how to do this?


#1

Anyone know how to round a number to something like the following?

On GPS systems I’ve seen that it rounds the distance as you approach a junction to around 50 meters. For my code for a different purpose, I want to round the number to 5 so that it only shows 0, 5, 10, 15 etc.

What’s the easiest way to do this in NETMF?


#2

Would this work:

Mod5Value = Value%5;

RoundedValue = Mod5Value < 3 ? (Value - Mod5Value) : (Value + 5 - Mod5Value);

P.S. I learned from some old school guys, and therefore love ternary operators :slight_smile:


#3

I don’t use .NET as much any more so I can’t give the exact syntax, but mathematically you can do the following

nearest5 = Math.Round(value / 5) * 5

This would round up to the closest 5, for example 3 would go to 5 while 0, 1, 2 would go to 0, also 10, 11, 12 would return 10 while 13…17 would return 15.


#4

Thanks for the solutions. I’ll give them both a try out this week.