Reputation: 137
I am in the middle of making a calculator in C# and I want to round to nearest 1, 10, 100, etc and also like nearsest 0.1, 0.001, etc. I have seen other projects that tell me how to do it but I tried and they don't seem to work.
I've tried:
textBox1.Text = Convert.ToString(Math.Round(Convert.ToDouble(Label1.Text), Convert.ToInt32(textBox1.Text), MidpointRounding.AwayFromZero));
and...
textBox1.Text = Convert.ToString(Math.Round(Convert.ToDouble(Label1.Text), Convert.ToInt32(textBox1.Text)));
and...
textBox1.Text = Convert.ToString(Convert.ToInt32(Label1.Text) / Convert.ToInt32(textBox1.Text) * Convert.ToInt32(textBox1.Text));
Upvotes: 2
Views: 3093
Reputation: 749
You can make an Extension method to do it, using the same idea from Jonathon's answer. You divide the input by the interval you choose, round it using Math.Round
, and then multiply the rounded number by the interval.
static class Extensions
{
public static int RoundToInterval(this int i, int interval)
{
if (interval == 0)
{
throw new ArgumentException("The specified interval cannot be 0.", nameof(interval));
}
return ((int)Math.Round((double)i / (double)interval)) * interval;
}
}
Calling it will look like so.
int input = 13;
var result = input.RoundToInterval(10);
The result of the previous example call will be 10
. Change input
to 16, and the result will be 20
. If you pass 100 as the argument to RoundToInterval
, the result will be 0
, and 51 (and 50 with the default MidpointRounding choice) will give the result of 100
.
Upvotes: 1
Reputation: 9704
Math.Round has overloads that allow you to round to a particular decimal.
e.g.
Math.Round(0.05, 1, MidpointRounding.AwayFromZero);
will result in 0.1
If you want to round to the nearest 10, 100, etc, you will need to do a bit more math.
Math.Round((double)50 / 100, MidpointRounding.AwayFromZero) * 100;
results in 100, for rounding to the nearest hundred, while
Math.Round((double)55 / 10, MidpointRounding.AwayFromZero) * 10;
will get you to the nearest 10, in this case 60.
Upvotes: 5