trimming left digit of a number

  • Thread starter Thread starter Guest
  • Start date Start date
G

Guest

How do I trim the left digit from a number? The user will input a number with
3 digit value and I need to trim the leftmost value from the number. A
typical value might be 123.4567 and I need to remove the 1 and use it's value
in another calculation.
 
If the number is still in textual form you can use string operations:

string leftMostDigit = textualForm.Substring(0, 1);

Even faster is to grab the character:

char leftMostChar = textualForm[0];
int value = leftMostChar - '0';
if ( value < 0 || value > 9 ) { // Error }

If you are working with numbers then I would recommend converting
the item to an integer (trims the decimal locations) and then dividing by
10 until you are left with a value less than 10. Of course if the number is
3 digits, you can divide by 100 after validating the data is greater than
99 and less than 1000.
 
Justin Rogers wrote:

[...snip...]
If you are working with numbers then I would recommend converting
the item to an integer (trims the decimal locations) and then dividing by
10 until you are left with a value less than 10. Of course if the number is
3 digits, you can divide by 100 after validating the data is greater than
99 and less than 1000.
[...snip...]

Or you might as well use the modulo operator:

123.456 % 100 ==> 23.456
456.789 % 100 ==> 56.789
78 % 100 ==> 78

The % operator is defined for all numeric types.
 
Back
Top