1

How would I go about round off floats ONLY to multiples of 0.025

So for example: 1.041 would be rounded off to 1.05

I know how to round off floats in C# but only to decimal values.

JJ Harris
  • 13
  • 4
  • 6
    i want to upvote cos its an interesting challenge, but downvote because you havent tried anyting – pm100 Sep 27 '18 at 19:05
  • 2
    multiply by 400 and put the result in an int. now place that in a float and divice by 400 – pm100 Sep 27 '18 at 19:08
  • Here's a question/answer that is very similar to what you're asking here. https://stackoverflow.com/questions/2826262/round-a-decimal-to-the-nearest-quarter-in-c-sharp – Beska Sep 27 '18 at 20:34
  • @pm100 I didn't even know where to start trying :(. I have a book on C# by John Sharp and looked online but could not find anything even remotely useful. – JJ Harris Oct 02 '18 at 13:17
  • @beska Thank you. That makes sense. I had looked into Math.round but it didn't seem useful because I didn't know about MidpointRounding – JJ Harris Oct 02 '18 at 13:20

2 Answers2

1

Modified from here

public static float QuarterTenthsRound(this float number)
{
     var decimalPlaces = number - (int)number;

     float wholeNumber = (float)((Math.Round((decimalPlaces * 10) * 4, 
           MidpointRounding.ToEven) / 4) / 10);            

     return (int)number + wholeNumber;
}

I used it as an extension method, so myFloat.QuarterTenthsRound() would be the usage.

Austin T French
  • 5,022
  • 1
  • 22
  • 40
0

You could use a function like this:

public static decimal Round(decimal value)
{
    var ceiling = Math.Ceiling(value * 400);

    return ceiling / 400;
}
bumble_bee_tuna
  • 3,533
  • 7
  • 43
  • 83