user2234078
user2234078

Reputation: 19

Get Integer Upper and Lower Value Range

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

Answers (3)

Idle_Mind
Idle_Mind

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

Matthew Watson
Matthew Watson

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:

  1. Use (int)Math.Log10() to work out the nearest power of 10 for the value.
  2. Use that with Math.Pow() and rounding to give a whole number that is a power of 10.
  3. Round off the digits below that power of 10 by dividing by it, then multiplying just the integer part of the result by it,
  4. The upper will simply be the lower plus that power of 10.

Note that it is crucial that value is an integer.

Upvotes: 1

Nikola Davidovic
Nikola Davidovic

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

Related Questions