MathGroup Archive 2010

[Date Index] [Thread Index] [Author Index]

Search the Archive

Re: Simplest way to get 2 digits from an integer...

  • To: mathgroup at smc.vnet.net
  • Subject: [mg110971] Re: Simplest way to get 2 digits from an integer...
  • From: Raffy <adraffy at gmail.com>
  • Date: Thu, 15 Jul 2010 03:09:32 -0400 (EDT)
  • References: <i1e7p1$94p$1@smc.vnet.net>

On Jul 11, 10:04 pm, Murta <rodrigomur... at gmail.com> wrote:
> Hello All
>
> I would like to find a simplest code to take the first n digits os a integer.
> Here are two examples (not simple) to take the first 2 digits os the number a:
>
> 1)
> a = 1234;
> ToExpression@StringTake[ToString[a], 2]
> 12
>
> 2)
> a = 1234;
> FromDigits@Take[IntegerDigits[a],2]
> 12
> -------
> In Excel, I just use Left(a,2)*1 (multiply by 1 to get a number,
> instead of text)
> There is one simplest way in Mathematica!?
>
> thanks in advance
> Rodrigo Murta

ClearAll[takeDig];
takeDig[n_Integer, c_Integer, b_Integer:10] := Which[
   n == 0 || c == 0, 0,
   n < 0, -takeDig[-n, c, b],
   c > 0, Quotient[n, b^Ceiling[Log[b, n + 1] - c]],
   c < 0, Mod[n, b^-c]
   ];


takeDig[12345,3] === 123
takeDig[12345,-3] === 345
takeDig[-12345,3] === -123
takeDig[-12345,-3] === -345
takeDig[10000, 1] === 1
takeDig[10000, -4] === 0
takeDig[0, _] === 0
takeDig[_, 0] === 0

Or, if you just want the n > and c > 0 case:

takeDig[n_, c_] := Quotient[n, 10^Ceiling[Log10[n + 1] - c]];


  • Prev by Date: Accessing static members with J/Link
  • Next by Date: Re: Tooltip text to Clipboard ?
  • Previous by thread: Re: Simplest way to get 2 digits from an integer...
  • Next by thread: strange bahavior of ArcSinh