10

Is there a way to check a length of an integer variable, and if is too long just trim it? I have a field in a database that accepts 3 characters. Length is 3.

So is it possible to do like it's done with string variable?

example:

cust_ref = cust_ref.Length > 20 ? cust_ref.Substring(0, 19) : cust_ref; 

Thanks!

2
  • If you have a field in a database that is storing an integer, why is it a character-type field, not an integer? The lazy answer here would be "4 bytes; an int is always 4 bytes". Commented Jun 1, 2012 at 7:42
  • $"{value}".Length Commented Nov 5, 2023 at 9:59

10 Answers 10

41

The easiest answer would be:

//The length would be 3 chars.    
public int myint = 111;
myint.ToString().Length;
Sign up to request clarification or add additional context in comments.

Comments

22

The following worked a treat for me!

public static int IntLength(int i)
{
  if (i < 0)
    throw new ArgumentOutOfRangeException();
  if (i == 0)
    return 1;
  return (int)Math.Floor(Math.Log10(i)) + 1;
}

Original Source: http://www.java2s.com/Code/CSharp/Data-Types/Getthedigitlengthofanintvalue.htm

2 Comments

var result = (int)Math.Floor(Math.Log10(Math.Abs(cust_ref)) + (cust_ref > 0 ? 1d : 2d))
With handling of 0, negative integers and int.MinValue: var result = cust_ref == 0 ? 1 : (int)Math.Floor(Math.Log10(Math.Abs((double)cust_ref))) + (cust_ref > 0 ? 1 : 2);
5

You don't have to convert it to a string to make it shorter, that can be done numerically:

if (num > 999) {
  num %= 1000;
}

This will cut of digits from the left, if you want to cut them off from the right:

while (num > 999) {
  num /= 10;
}

If the value can be negative, also check:

if (num < -99) {
  num = -(-num % 100);
}

or:

while (num < -99) {
  num = -(-num / 10);
}

Comments

1
cust_ref = cust_ref.ToString().Length > 20 ? Convert.ToInt32(cust_ref.ToString().Substring(0, 19)) : cust_ref; 

or simply use

cust_ref = Convert.ToInt32(Convert.ToString(cust_ref).Substring(0, 19));

3 Comments

Ok I got it, the key is to convert a variable to string.. Thanks!
The second version only works if the value always is at least 19 characters, otherwise you get an ArgumentOutOfRangeException.
int -> string -> string -> int :(
1

Use like this

 cust_ref=   cust_ref.Tostring().Length > 20 ? Convert.ToInt32(cust_ref.ToString().Substring(0, 19)) : cust_ref; 

1 Comment

This code will create 3 additional string instancies if it executes
1

Nont very clear what you're asking for, but as much as I unerstood you're asking for:

int a = 1234567890; 

for some reason you want to make it shorter, like

 int b = MakeShorter(a); 
    //b == 1234 (say)

If so, the easiest solution may be, convert it to string, made what you already implemented and reconvert it back to int.

If this is not what you're asking for, please clarify.

2 Comments

That it, if variable is to long I have to trim it, so first I have to convert it to string and then back to int?
@CrBruno: In my opinion this is an easiest solution.
1

The conversion to the string is ugly way to implement it.

It's require a pure math solution

int CutTheNumber(int number, int maxLen)
{
  var maxSize = (int)Math.Pow(10, maxlen);
  if(maxSize <= Math.Abs(number))
  {
    number %= maxSize;
  }

  return number;
}

8 Comments

No it doesn't require a numerical solution.
I'm sorry but I don't understand you :(
You said that it requires a pure math solution, but that's not true. Other solutions work as well, it's just a matter of taste.
You are right all of them are working but they aren't working well! The strings' processing is so cost, it's critical to lot of applications until you are writing CD-ejector.
Then you should remove the costly floating point operation from your code. That would make it about ten times faster.
|
0

Checking length

     length = cust_ref.ToString().Length;

Remove extra bits

       if (length > need)
       {
           cust_ref =Convert.ToInt32( cust_ref.ToString().Remove(length -(length- need)));
       }

Comments

0

for this u will have to do some simple stuffs. like

cust_ref = Convert.ToInt32(Convert.ToString(cust_ref).Substring(0, 19));

or u can manually store it in any variable and the

Comments

0

You can try this code. use if else statement to check the validation ..

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace avaragescore
{
    class Program
    {

        static void Main(string[] args)
        {
            float quiz;
            float midterm;
            float final;
            float avrg=0;
        Start:
            Console.WriteLine("Please enter the Quize Score here");
            quiz = float.Parse(Console.ReadLine());
            if(quiz > 100)
            {
                Console.WriteLine("You have entered wrong score please re-enter");
                goto Start;
            }
            Start1:
            Console.WriteLine("Please enter the Midterm Score here");
            midterm = float.Parse(Console.ReadLine());
            if(midterm > 100)
            {
                Console.WriteLine("You have entered wrong score please re- enter");
                goto Start1;
            }
            Start3:
            Console.WriteLine("Please enter the Final Score here");
            final = float.Parse(Console.ReadLine());
            if(final > 100)
            {
                Console.WriteLine("You have entered wrong Score Please re-enter");
                goto Start3;
            }
            avrg = (quiz + midterm + final) / 3;

            if(avrg >= 90)
            {
                Console.WriteLine("Your Score is {0} , You got A grade",avrg);
            }
            else if (avrg >= 70 && avrg < 90)
            {
                Console.WriteLine("Your Score is {0} , You got B grade", avrg);
            }
            else if (avrg >= 50 && avrg < 70)
            {
                Console.WriteLine("Your Score is {0} , You got C grade", avrg);
            }
            else if (avrg < 50)
            {
                Console.WriteLine("Yor Score is {0} , You are fail", avrg);
            }
            else
            {
                Console.WriteLine("You enter invalid Score");
            }
            Console.ReadLine();
        }
    }
}

1 Comment

When answering a question using code, it's good form to explain what the code is doing and why it answers the asker's question. Could you add some of that to your answer?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.