"Substring" numeric value

In C #, which is the best way for a "substring" (due to the lack of a better word) to have a long meaning.

I need to calculate the sum of the account numbers for the trailer entry, but only 16 least significant characters are needed.

I can do this by converting the value to a string, but wondering if there is a better way in which this can be done.

long number = 1234567890123456789L;
const long _MAX_LENGTH = 9999999999999999L;

if (number > _MAX_LENGTH)
{
  string strNumber = number.ToString();
  number = Convert.ToInt64(strNumber.Substring(strNumber.Length - 16));
}

This will return the value 4567890123456789.

+3
source share
3 answers

You can do:

long number = 1234567890123456789L;
long countSignificant = 16;
long leastSignificant = number % (long) Math.Pow(10, countSignificant);

How it works? Well, if you divide by 10, you drop the last digit, right? Does the last digit remain? The same applies to 100, and 1000 Math.Pow(1, n).

Let's look at the least significant figure, because we can do it in our head:

1234, 10, 123 4

# :

1234 / 10 == 123;
1234 % 10 == 4;

, - , n . , , 10 n. # (, ** python), :

Math.Pow(10, 4) == 1000.0; // oops: a float!

:

(long) Math.Pow(10, 4) == 1000;

, , ;)

+8

modulo ( % #). :

123456 % 100000 = 23456

123456 % 1000 = 456

, , . , , , .

, :

long number = 1234567890123456789L;
long divisor = 10000000000000000L;
long result = number % divisor;
+7

, modulo:

long number = 1234567890123456789L;
const long _MAX_LENGTH = 9999999999999999L;

number = number % (_MAX_LENGTH + 1);                

Console.WriteLine (number);

Live test: http://ideone.com/pKB6w


Until you are enlightened by the modular approach, you can choose this option instead:

long number = 1234567890123456789L;
const long _MAX_LENGTH = 9999999999999999L;


if (number > _MAX_LENGTH) {             
    long minus = number / (_MAX_LENGTH +  1) * (_MAX_LENGTH +  1);              
    number = number - minus;
}

Console.WriteLine(number);

Live test: http://ideone.com/oAkcy

Strike>


Note:

Using a modular approach is strongly recommended; do not use subtraction. The Modulo approach is the best, without a corner case, that is, there is no need to use an operator if.

+1
source

All Articles