Reputation: 19
I am Writing C# Application where i have Employee Salary. How to get Upper and Lower Range of Salary Integer like 26500 is between 20000 and 30000. i want to find these two Values upper and lower for 26500. Like this if Salary Value is 1200 then its upper and lower values will be 1000 and 2000.
Upvotes: 1
Views: 1685
Reputation: 39122
I couldn't resist...a different "string" based approach that I'm sure many will simply hate:
int value = 26500;
int lower = Convert.ToInt32(value.ToString().Substring(0, 1) + new String('0', value.ToString().Length - 1));
int upper = lower + Convert.ToInt32("1" + new String('0', value.ToString().Length - 1));
Console.WriteLine(lower.ToString("N0") + " <= " + value.ToString("N0") + " <= " + upper.ToString("N0"));
Bonus: It doesn't puke on 0 (zero)...
Upvotes: 0
Reputation: 109567
int value = 26500; // Initialise this to whatever value you need.
int range = (int)(0.5 + Math.Pow(10, (int)Math.Log10(value)));
int lower = range*(value/range);
int upper = lower + range;
This works by:
Note that it is crucial that value
is an integer.
Upvotes: 1
Reputation: 8656
You could use something like the following code:
private void button1_Click(object sender, EventArgs e)
{
int a = 26500;
int powerOfTen = (int)Math.Pow(10, NumDigits(a)-1);
int lowerBound = a - a%powerOfTen;
int upperBound = (a/powerOfTen + 1) * powerOfTen;
}
private int NumDigits(int value)
{
int count = 0;
while (value > 0)
{
value /= 10;
count++;
}
return count;
}
The method NumDigits, as the name says, will count the number of digits of the desired number.
Upvotes: 3