Middle three digits: Difference between revisions

m
imported>Arakov
 
(72 intermediate revisions by 39 users not shown)
Line 13:
Show your output on this page.
<br><br>
 
=={{header|11l}}==
{{trans|Python}}
 
<syntaxhighlight lang="11l">F middle_three_digits(i)
V s = String(abs(i))
assert(s.len >= 3 & s.len % 2 == 1, ‘Need odd and >= 3 digits’)
R s[s.len I/ 2 - 1 .+ 3]
 
V passing = [123, 12345, 1234567, 987654321, 10001, -10001, -123, -100, 100, -12345]
V failing = [1, 2, -1, -10, 2002, -2002, 0]
L(x) passing [+] failing
X.try
V answer = middle_three_digits(x)
print(‘middle_three_digits(#.) returned: #.’.format(x, answer))
X.catch AssertionError error
print(‘middle_three_digits(#.) returned error: ’.format(x)‘’String(error))</syntaxhighlight>
 
{{out}}
<pre>
middle_three_digits(123) returned: 123
middle_three_digits(12345) returned: 234
middle_three_digits(1234567) returned: 345
middle_three_digits(987654321) returned: 654
middle_three_digits(10001) returned: 000
middle_three_digits(-10001) returned: 000
middle_three_digits(-123) returned: 123
middle_three_digits(-100) returned: 100
middle_three_digits(100) returned: 100
middle_three_digits(-12345) returned: 234
middle_three_digits(1) returned error: Need odd and >= 3 digits
middle_three_digits(2) returned error: Need odd and >= 3 digits
middle_three_digits(-1) returned error: Need odd and >= 3 digits
middle_three_digits(-10) returned error: Need odd and >= 3 digits
middle_three_digits(2002) returned error: Need odd and >= 3 digits
middle_three_digits(-2002) returned error: Need odd and >= 3 digits
middle_three_digits(0) returned error: Need odd and >= 3 digits
</pre>
 
=={{header|Action!}}==
{{libheader|Action! Tool Kit}}
{{libheader|Action! Real Math}}
<syntaxhighlight lang="action!">INCLUDE "H6:REALMATH.ACT"
INCLUDE "D2:PRINTF.ACT" ;from the Action! Tool Kit
 
PROC MiddleThreeDigits(REAL POINTER n CHAR ARRAY res)
REAL r
CHAR ARRAY s(15)
BYTE i
 
RealAbs(n,r)
StrR(r,s)
i=s(0)
IF i<3 OR (i&1)=0 THEN
res(0)=0
ELSE
i==RSH 1
SCopyS(res,s,i,i+2)
FI
RETURN
 
PROC Test(CHAR ARRAY s)
REAL n
CHAR ARRAY res(4)
 
ValR(s,n)
MiddleThreeDigits(n,res)
IF res(0) THEN
PrintF("%9S -> %S%E",s,res)
ELSE
PrintF("%9S -> error!%E",s)
FI
RETURN
 
PROC Main()
Put(125) PutE() ;clear the screen
 
Test("123") Test("12345")
Test("1234567") Test("987654321")
Test("10001") Test("-10001")
Test("-123") Test("-100")
Test("100") Test("-12345")
Test("1") Test("2")
Test("-1") Test("-10")
Test("2002") Test("-2002")
Test("0")
RETURN</syntaxhighlight>
{{out}}
[https://gitlab.com/amarok8bit/action-rosetta-code/-/raw/master/images/Middle_three_digits.png Screenshot from Atari 8-bit computer]
<pre>
123 -> 123
12345 -> 234
1234567 -> 345
987654321 -> 654
10001 -> 000
-10001 -> 000
-123 -> 123
-100 -> 100
100 -> 100
-12345 -> 234
1 -> error!
2 -> error!
-1 -> error!
-10 -> error!
2002 -> error!
-2002 -> error!
0 -> error!
</pre>
 
=={{header|Ada}}==
 
<langsyntaxhighlight Adalang="ada">with Ada.Text_IO;
 
procedure Middle_Three_Digits is
Line 58 ⟶ 166:
end loop;
 
end Middle_Three_Digits;</langsyntaxhighlight>
 
{{out}}
Line 80 ⟶ 188:
 
=={{header|Aime}}==
<langsyntaxhighlight lang="aime">void
m3(integer i)
{
Line 120 ⟶ 228:
 
return 0;
}</langsyntaxhighlight>
{{out}}
<pre> 123: 123
Line 142 ⟶ 250:
=={{header|ALGOL 68}}==
{{works with|ALGOL 68G|Any - tested with release 2.6.win32}}
<langsyntaxhighlight lang="algol68"># we define a UNION MODE so that our middle 3 digits PROC can #
# return either an integer on success or a error message if #
# the middle 3 digits couldn't be extracted #
Line 204 ⟶ 312:
print( ( newline ) )
OD
)</langsyntaxhighlight>
{{out}}
<pre>
Line 227 ⟶ 335:
 
=={{header|ALGOL W}}==
<langsyntaxhighlight lang="algolw">begin
% record structure that will be used to return the middle 3 digits of a number %
% if the middle three digits can't be determined, isOk will be false and message %
Line 274 ⟶ 382:
end for_n
 
end.</langsyntaxhighlight>
{{out}}
<pre>
Line 295 ⟶ 403:
0: Number must have at least 3 digits
</pre>
 
=={{header|Amazing Hopper}}==
<p>VERSION 1:</p>
<syntaxhighlight lang="c">
#include <basico.h>
 
algoritmo
n=0, c=""
temp = 0, candidatos={}
'123, 12345, 1234567, 987654321, 10001, -10001,-123'
'-100, 100, -12345,1, 2, -1, -10, 2002, -2002, 0'
enlistar en 'candidatos'
decimales '0'
 
#basic{
temp = string(candidatos * sign(candidatos))
n = len( temp )
c = replicate (temp, n>=3 && not(is even(n)))
toksep(NL)
print (cat( lpad(" ",11,string(candidatos)), cat(" : ", copy( 3, (n/2-1), c ))),NL)
}
terminar
 
</syntaxhighlight>
{{out}}
<pre>
123 : 123
12345 : 234
1234567 : 345
987654321 : 654
10001 : 000
-10001 : 000
-123 : 123
-100 : 100
100 : 100
-12345 : 234
1 :
2 :
-1 :
-10 :
2002 :
-2002 :
0 :
 
</pre>
<p>VERSION 2:</p>
<syntaxhighlight lang="c">
#include <basico.h>
 
algoritmo
n=0, c="",
temp = 0, candidatos={}
'123, 12345, 1234567, 987654321, 10001, -10001,-123'
'-100, 100, -12345,1, 2, -1, -10, 2002, -2002, 0'
enlistar en 'candidatos'
decimales '0'
tomar 'candidatos', quitar el signo
convertir a cadena ---retener---, obtener largo, mover a 'n',
guardar en 'temp'
guardar ' replicar ( temp, #(n>=3 && not(is even(n))))' en 'c'
token.separador(NL)
justificar derecha(11,#(string(candidatos))), " : ", concatenar esto
#( copy( 3, (n/2-1), c ) ), unir esto
luego imprime
terminar
</syntaxhighlight>
{{out}}
<pre>
123 : 123
12345 : 234
1234567 : 345
987654321 : 654
10001 : 000
-10001 : 000
-123 : 123
-100 : 100
100 : 100
-12345 : 234
1 :
2 :
-1 :
-10 :
2002 :
-2002 :
0 :
</pre>
 
<p>VERSION 3:</p>
<syntaxhighlight lang="c">
#include <basico.h>
 
algoritmo
n=0, c="", m=0,
candidatos={}
'123, 12345, 1234567, 987654321, 10001, -10001,-123'
'-100, 100, -12345,1, 2, -1, -10, 2002, -2002, 0'
enlistar en 'candidatos'
decimales '0'
para cada elemento (v,candidatos,17)
tomar'v' ---copiar en 'm'---, quitar el signo
guardar en 'v'
#(len( c:=(string(v)) ) ), mover a 'n'
"Num: ",justificar derecha(10,#(string(m))),"(",n,")\t"
si ' #( n>=3 && not(is even(n))) '
" puede ser procesado : "
tomar si ( #(n==3), 'c', #( copy( 3, (n/2-1), c )) ), NL
sino
"no puede ser procesado\n"
fin si
luego imprime
siguiente
 
terminar
</syntaxhighlight>
{{out}}
<pre>
Num: 123(3) puede ser procesado : 123
Num: 12345(5) puede ser procesado : 234
Num: 1234567(7) puede ser procesado : 345
Num: 987654321(9) puede ser procesado : 654
Num: 10001(5) puede ser procesado : 000
Num: -10001(5) puede ser procesado : 000
Num: -123(3) puede ser procesado : 123
Num: -100(3) puede ser procesado : 100
Num: 100(3) puede ser procesado : 100
Num: -12345(5) puede ser procesado : 234
Num: 1(1) no puede ser procesado
Num: 2(1) no puede ser procesado
Num: -1(1) no puede ser procesado
Num: -10(2) no puede ser procesado
Num: 2002(4) no puede ser procesado
Num: -2002(4) no puede ser procesado
Num: 0(1) no puede ser procesado
 
</pre>
 
=={{header|AppleScript}}==
===Procedural===
987654321 is too large to be represented as an AppleScript integer, so "integer value" is taken here to refer to the numeric value rather than to the language class. AppleScript automatically coerces numeric text and single-item lists to appropriate number classes where necessary and possible, so these are acceptable as parameters too.
 
<syntaxhighlight lang="applescript">on middle3Digits(n)
try
n as number -- Errors if n isn't a number or coercible thereto.
set s to n as text -- Keep for the ouput string.
if (n mod 1 is not 0) then error (s & " isn't an integer value.")
if (n < 0) then set n to -n
if (n < 100) then error (s & " has fewer than three digits.")
-- Coercing large numbers to text may result in E notation, so extract the digit values individually.
set theDigits to {}
repeat until (n = 0)
set beginning of theDigits to n mod 10 as integer
set n to n div 10
end repeat
set c to (count theDigits)
if (c mod 2 is 0) then error (s & " has an even number of digits.")
on error errMsg
return "middle3Digits handler got an error: " & errMsg
end try
set i to (c - 3) div 2 + 1
set {x, y, z} to items i thru (i + 2) of theDigits
return "The middle three digits of " & s & " are " & ((x as text) & y & z & ".")
end middle3Digits
 
-- Test code:
set testNumbers to {123, 12345, 1234567, "987654321", "987654321" as number, 10001, -10001, -123, -100, 100, -12345, 1, 2, -1, -10, 2002, -2002, 0}
set output to {}
repeat with thisNumber in testNumbers
set end of output to middle3Digits(thisNumber)
end repeat
set astid to AppleScript's text item delimiters
set AppleScript's text item delimiters to linefeed
set output to output as text
set AppleScript's text item delimiters to astid
return output</syntaxhighlight>
 
{{output}}
<syntaxhighlight lang="applescript">"The middle three digits of 123 are 123.
The middle three digits of 12345 are 234.
The middle three digits of 1234567 are 345.
The middle three digits of 987654321 are 654.
The middle three digits of 9.87654321E+8 are 654.
The middle three digits of 10001 are 000.
The middle three digits of -10001 are 000.
The middle three digits of -123 are 123.
The middle three digits of -100 are 100.
The middle three digits of 100 are 100.
The middle three digits of -12345 are 234.
middle3Digits handler got an error: 1 has fewer than three digits.
middle3Digits handler got an error: 2 has fewer than three digits.
middle3Digits handler got an error: -1 has fewer than three digits.
middle3Digits handler got an error: -10 has fewer than three digits.
middle3Digits handler got an error: 2002 has an even number of digits.
middle3Digits handler got an error: -2002 has an even number of digits.
middle3Digits handler got an error: 0 has fewer than three digits."</syntaxhighlight>
 
===Functional===
<syntaxhighlight lang="applescript">-------------------- MID THREE DIGITS ---------------------
 
-- mid3digits :: Int -> Either String String
on mid3digits(n)
-- Either a message explaining why
-- no "mid 3 digits" are defined for n,
-- or the mid 3 digits themselves.
set m to abs(n)
if 100 > m then
|Left|("Less than 3 digits")
else if maxBound(1) < m then
|Left|("Out of AppleScript integer range")
else
set s to m as string
set intDigits to length of s
if even(intDigits) then
|Left|("Even digit count")
else
|Right|((items 1 thru 3 of ¬
items (1 + ((intDigits - 3) div 2)) thru -1 of s) as string)
end if
end if
end mid3digits
 
 
-------------------------- TEST ---------------------------
on run
set ints to map(readInt, splitOn(", ", ¬
"123, 12345, 1234567, 987654321, 10001, -10001, " & ¬
"-123, -100, 100, -12345, 1, 2, -1, -10, 2002, -2002, 0"))
script showResult
on |λ|(x)
either(my bracketed, my str, x)
end |λ|
end script
fTable("Mid three digits:", str, showResult, mid3digits, ints)
end run
 
 
------------------------ GENERICS -------------------------
 
-- Left :: a -> Either a b
on |Left|(x)
{type:"Either", |Left|:x, |Right|:missing value}
end |Left|
 
 
-- Right :: b -> Either a b
on |Right|(x)
{type:"Either", |Left|:missing value, |Right|:x}
end |Right|
 
 
-- abs :: Num -> Num
on abs(x)
-- Absolute value.
if 0 > x then
-x
else
x
end if
end abs
 
 
-- even :: Int -> Bool
on even(x)
0 = x mod 2
end even
 
 
-- maxBound :: a -> a
on maxBound(x)
set c to class of x
if text is c then
character id 65535
else if integer is c then
(2 ^ 29 - 1)
else if real is c then
1.797693E+308
else if boolean is c then
true
end if
end maxBound
 
 
-------------------- GENERICS FOR TEST AND DISPLAY ---------------------
 
-- bracketed :: String -> String
on bracketed(s)
"(" & s & ")"
end bracketed
 
 
-- compose (<<<) :: (b -> c) -> (a -> b) -> a -> c
on compose(f, g)
script
property mf : mReturn(f)
property mg : mReturn(g)
on |λ|(x)
mf's |λ|(mg's |λ|(x))
end |λ|
end script
end compose
 
 
-- either :: (a -> c) -> (b -> c) -> Either a b -> c
on either(lf, rf, e)
if missing value is |Left| of e then
tell mReturn(rf) to |λ|(|Right| of e)
else
tell mReturn(lf) to |λ|(|Left| of e)
end if
end either
 
 
-- foldl :: (a -> b -> a) -> a -> [b] -> a
on foldl(f, startValue, xs)
tell mReturn(f)
set v to startValue
set lng to length of xs
repeat with i from 1 to lng
set v to |λ|(v, item i of xs, i, xs)
end repeat
return v
end tell
end foldl
 
 
-- fTable :: String -> (a -> String) -> (b -> String) -> (a -> b) -> [a] -> String
on fTable(s, xShow, fxShow, f, xs)
set ys to map(xShow, xs)
set w to maximum(map(my |length|, ys))
script arrowed
on |λ|(a, b)
justifyRight(w, space, a) & " -> " & b
end |λ|
end script
s & linefeed & unlines(zipWith(arrowed, ¬
ys, map(compose(fxShow, f), xs)))
end fTable
 
 
-- justifyRight :: Int -> Char -> String -> String
on justifyRight(n, cFiller, strText)
if n > length of strText then
text -n thru -1 of ((replicate(n, cFiller) as text) & strText)
else
strText
end if
end justifyRight
 
 
-- length :: [a] -> Int
on |length|(xs)
set c to class of xs
if list is c or string is c then
length of xs
else
(2 ^ 29 - 1) -- (maxInt - simple proxy for non-finite)
end if
end |length|
 
 
-- map :: (a -> b) -> [a] -> [b]
on map(f, xs)
-- The list obtained by applying f
-- to each element of xs.
tell mReturn(f)
set lng to length of xs
set lst to {}
repeat with i from 1 to lng
set end of lst to |λ|(item i of xs, i, xs)
end repeat
return lst
end tell
end map
 
 
-- maximum :: Ord a => [a] -> a
on maximum(xs)
script
on |λ|(a, b)
if a is missing value or b > a then
b
else
a
end if
end |λ|
end script
foldl(result, missing value, xs)
end maximum
 
 
-- min :: Ord a => a -> a -> a
on min(x, y)
if y < x then
y
else
x
end if
end min
 
 
-- mReturn :: First-class m => (a -> b) -> m (a -> b)
on mReturn(f)
-- 2nd class handler function lifted into 1st class script wrapper.
if script is class of f then
f
else
script
property |λ| : f
end script
end if
end mReturn
 
 
-- readInt :: String -> Int
on readInt(s)
s as integer
end readInt
 
 
-- Egyptian multiplication - progressively doubling a list, appending
-- stages of doubling to an accumulator where needed for binary
-- assembly of a target length
-- replicate :: Int -> a -> [a]
on replicate(n, a)
set out to {}
if 1 > n then return out
set dbl to {a}
repeat while (1 < n)
if 0 < (n mod 2) then set out to out & dbl
set n to (n div 2)
set dbl to (dbl & dbl)
end repeat
return out & dbl
end replicate
 
 
-- splitOn :: String -> String -> [String]
on splitOn(pat, src)
set {dlm, my text item delimiters} to ¬
{my text item delimiters, pat}
set xs to text items of src
set my text item delimiters to dlm
return xs
end splitOn
 
 
-- str :: a -> String
on str(x)
x as string
end str
 
 
-- unlines :: [String] -> String
on unlines(xs)
-- A single string formed by the intercalation
-- of a list of strings with the newline character.
set {dlm, my text item delimiters} to ¬
{my text item delimiters, linefeed}
set s to xs as text
set my text item delimiters to dlm
s
end unlines
 
 
-- zipWith :: (a -> b -> c) -> [a] -> [b] -> [c]
on zipWith(f, xs, ys)
set lng to min(length of xs, length of ys)
set lst to {}
if 1 > lng then
return {}
else
tell mReturn(f)
repeat with i from 1 to lng
set end of lst to |λ|(item i of xs, item i of ys)
end repeat
return lst
end tell
end if
end zipWith</syntaxhighlight>
{{Out}}
<pre>Mid three digits:
123 -> 123
12345 -> 234
1234567 -> 345
9.87654321E+8 -> (Out of AppleScript integer range)
10001 -> 000
-10001 -> 000
-123 -> 123
-100 -> 100
100 -> 100
-12345 -> 234
1 -> (Less than 3 digits)
2 -> (Less than 3 digits)
-1 -> (Less than 3 digits)
-10 -> (Less than 3 digits)
2002 -> (Even digit count)
-2002 -> (Even digit count)
0 -> (Less than 3 digits)</pre>
 
=={{header|Arturo}}==
 
<syntaxhighlight lang="rebol">middleThree: function [num][
n: to :string abs num
if 3 > size n -> return "Number must have at least three digits"
if even? size n -> return "Number must have an odd number of digits"
 
middle: ((size n)/2)- 1
return slice n middle middle+2
]
 
samples: @[
123, 12345, 1234567, 987654321, 10001, neg 10001, neg 123, neg 100, 100, neg 12345,
1, 2, neg 1, neg 10, 2002, neg 2002, 0
]
 
loop samples 's [
print [pad to :string s 10 ":" middleThree s]
]</syntaxhighlight>
 
{{out}}
 
<pre> 123 : 123
12345 : 234
1234567 : 345
987654321 : 654
10001 : 000
-10001 : 000
-123 : 123
-100 : 100
100 : 100
-12345 : 234
1 : Number must have at least three digits
2 : Number must have at least three digits
-1 : Number must have at least three digits
-10 : Number must have at least three digits
2002 : Number must have an odd number of digits
-2002 : Number must have an odd number of digits
0 : Number must have at least three digits</pre>
 
=={{header|ATS}}==
<syntaxhighlight lang="ats">
<lang ATS>
(* ****** ****** *)
//
Line 418 ⟶ 1,088:
 
(* ****** ****** *)
</syntaxhighlight>
</lang>
{{out}}
<pre>Middle-three-digits(123): 123
Line 439 ⟶ 1,109:
 
=={{header|AutoHotkey}}==
<langsyntaxhighlight AutoHotkeylang="autohotkey">Numbers:="123,12345,1234567,987654321,10001,-10001,-123,-100,100,-12345,1,2,-1,-10,2002,-2002,0"
Loop, parse, Numbers, `,
{
Line 451 ⟶ 1,121:
log := log . A_LoopField . "`t: " . SubStr(n,((d-3)//2)+1,3) . "`n"
}
MsgBox % log</langsyntaxhighlight>
{{out}}
<pre>123 : 123
Line 472 ⟶ 1,142:
 
=={{header|AWK}}==
<langsyntaxhighlight AWKlang="awk">#!/bin/awk -f
# use as: awk -f middle_three_digits.awk
 
Line 500 ⟶ 1,170:
}
}
</syntaxhighlight>
</lang>
{{out}}
<pre>
Line 524 ⟶ 1,194:
=={{header|BASIC}}==
==={{header|Applesoft BASIC}}===
<langsyntaxhighlight ApplesoftBasiclang="applesoftbasic">100 DEF FN L(N) = LEN(STR$(INT(ABS(N))))
110 DEF FN N(N) = VAL(MID$(STR$(INT(ABS(N))),(FN L(N)-1)/2,3))
120 DEF FN EVEN(N) = INT(N/2) = N/2
Line 546 ⟶ 1,216:
300 DATA123,12345,1234567,987654321,10001,-10001,-123,-100,100,-12345
310 DATA1,2,-1,-10,2002,-2002,0
</syntaxhighlight>
</lang>
{{out}}
<pre>
Line 567 ⟶ 1,237:
0: ?ONLY 1 DIGIT
</pre>
 
==={{header|BASIC256}}===
<syntaxhighlight lang="vb">function middleThreeDigits(n)
if n < 0 then n = -n
if n < 100 then return "" ## error code
if n < 1000 then return string(n)
if n < 10000 then return ""
ns = string(n)
if length(ns) mod 2 = 0 then return "" ## need to have an odd number of digits for there to be 3 middle
return mid(ns, length(ns) \ 2, 3)
end function
 
dim a = {123, 12345, 1234567, 987654321, 10001, -10001, -123, -100, 100, -123451, 2, -1, -10, 2002, -2002, 0}
 
print "The 3 middle digits of the following numbers are : "
print
for i = 0 to 15
result = middleThreeDigits(a[i])
print a[i]; chr(9); " => ";
if result <> "" then
print result
else
print "Error: does not have 3 middle digits"
end if
next</syntaxhighlight>
{{out}}
<pre>Similar to FreeBASIC entry.</pre>
 
==={{header|BBC BASIC}}===
<langsyntaxhighlight lang="bbcbasic">REM >midthree
FOR i% = 1 TO 17
READ test%
Line 589 ⟶ 1,286:
OTHERWISE
= MID$(n$, LEN n$ / 2, 3)
ENDCASE</langsyntaxhighlight>
{{out}}
<pre> 123 -> 123
Line 610 ⟶ 1,307:
 
==={{header|FBSL}}===
<langsyntaxhighlight lang="qbasic">#APPTYPE CONSOLE
 
DIM numbers AS STRING = "123,12345,1234567,987654321,10001,-10001,-123,-100,100,-12345,1,2,-1,-10,2002,-2002,0"
Line 654 ⟶ 1,351:
RETURN m
END IF
END FUNCTION</langsyntaxhighlight>
Output
<pre> 123 --> 123
Line 677 ⟶ 1,374:
 
==={{header|IS-BASIC}}===
<langsyntaxhighlight ISlang="is-BASICbasic">100 INPUT PROMPT "Number: ":N
120 PRINT MIDDLE$(N)
130 DEF MIDDLE$(N)
Line 685 ⟶ 1,382:
170 LET P=(LEN(N$)-3)/2
180 LET MIDDLE$=N$(P+1:P+3)
190 END DEF</langsyntaxhighlight>
 
 
==={{header|PureBasic}}===
<langsyntaxhighlight lang="purebasic">Procedure.s middleThreeDigits(x.q)
Protected x$, digitCount
 
Line 716 ⟶ 1,413:
Print(#crlf$ + #crlf$ + "Press ENTER to exit"): Input()
CloseConsole()
EndIf</langsyntaxhighlight>
Sample output:
<pre> 123 : 123
Line 737 ⟶ 1,434:
 
==={{header|Run BASIC}}===
<langsyntaxhighlight lang="runbasic">x$ = "123, 12345, 1234567, 987654321, 10001, -10001, -123, -100, 100, -12345, 1, 2, -1, -10, 2002, -2002, 0"
 
while word$(x$,i+1,",") <> ""
Line 749 ⟶ 1,446:
end if
wend
end</langsyntaxhighlight>
<pre>123 123
234 12345
Line 767 ⟶ 1,464:
-2002 length < 3 or is even
0 length < 3 or is even</pre>
 
==={{header|Yabasic}}===
<syntaxhighlight lang="vb">sub middleThreeDigits$ (n)
if n < 0 n = -n
if n < 100 return "" // error code
if n < 1000 return str$(n)
if n < 10000 return ""
ns$ = str$(n)
if mod(len(ns$), 2) = 0 return "" // need to have an odd number of digits for there to be 3 middle
return mid$(ns$, len(ns$) / 2, 3)
end sub
 
dim a(16)
a(0) = 123 : a(1) = 12345 : a(2) = 1234567
a(3) = 987654321 : a(4) = 10001 : a(5) = -10001
a(6) = -123 : a(7) = -100 : a(8) = 100
a(9) = -123451
a(10) = 2 : a(11) = -1 : a(12) = -10
a(13) = 2002 : a(14) = -2002 : a(15) = 0
 
print "The 3 middle digits of the following numbers are : \n"
 
for i = 1 to 16
result$ = middleThreeDigits$(a(i))
print a(i), "\t => ";
if result$ <> "" then
print result$
else
print "Error: does not have 3 middle digits"
fi
next</syntaxhighlight>
{{out}}
<pre>Similar to FreeBASIC entry.</pre>
 
=={{header|Batch File}}==
<langsyntaxhighlight lang="dos">@echo off
setlocal enabledelayedexpansion
 
Line 814 ⟶ 1,544:
)
goto :EOF
%==/The Procedure ==%</langsyntaxhighlight>
{{Out}}
<pre>123: 123
Line 835 ⟶ 1,565:
 
Press any key to continue . . .</pre>
 
 
=={{header|Befunge}}==
Reads the integer value from stdin and writes the middle three digits (or an error message) to stdout.
 
<langsyntaxhighlight lang="befunge">>&>:0`2*1-*0>v
v+*86%+55:p00<
>\55+/:00g1+\|
Line 847 ⟶ 1,576:
2^,+55_,#!>#:<
>/>\#<$#-:#1_v
>_@#<,+55,,,$<</langsyntaxhighlight>
 
{{out}} (multiple runs)
Line 886 ⟶ 1,615:
 
=={{header|Bracmat}}==
<langsyntaxhighlight lang="bracmat">( ( middle3
= x p
. @(!arg:? [?p:? [(1/2*!p+-3/2) %?x [(1/2*!p+3/2) ?)
Line 901 ⟶ 1,630:
&
);
</syntaxhighlight>
</lang>
Output:
<pre>123
Line 923 ⟶ 1,652:
=={{header|Burlesque}}==
 
<langsyntaxhighlight lang="blsq">
blsq ) {123 12345 1234567 987654321 -10001 -123}{XX{~-}{L[3.>}w!m]\[}m[uN
123
Line 931 ⟶ 1,660:
000
123
</syntaxhighlight>
</lang>
 
<tt>m]\[</tt> and <tt>uN</tt> are just for displaying it nicely.
Line 937 ⟶ 1,666:
=={{header|C}}==
This code is followed by its output.
<syntaxhighlight lang="c">
<lang c>
#include <stdio.h>
#include <stdlib.h>
Line 969 ⟶ 1,698:
}
return 0;
}</langsyntaxhighlight>
 
<pre>
Line 993 ⟶ 1,722:
===Alternative Version===
This code has been extensively rewritten. The original was purely interactive and had to be invoked each time from the console. It also did not produce the correct answer.
<syntaxhighlight lang="c">
<lang c>
#include <stdio.h>
#include <stdlib.h>
Line 1,049 ⟶ 1,778:
}
}</langsyntaxhighlight>
 
{{out}}
Line 1,073 ⟶ 1,802:
Error, 0 is too short.
The middle three digits of 1234567890 are 456.
</pre>
 
=={{header|C_sharp|C#}}==
<lang csharp>using System;
 
namespace RosettaCode
{
class Program
{
static void Main(string[] args)
{
string text = Math.Abs(int.Parse(Console.ReadLine())).ToString();
Console.WriteLine(text.Length < 2 || text.Length % 2 == 0 ? "Error" : text.Substring((text.Length - 3) / 2, 3));
}
}
}</lang>
{{out}}
<pre>123:123
12345:234
1234567:345
987654321:654
10001:000
-10001:000
-123:123
-100:100
100:100
-12345:234
 
1:Error
2:Error
-1:Error
-10:Error
2002:Error
-2002:Error
0:Error
</pre>
 
=={{header|C++}}==
<langsyntaxhighlight lang="cpp">#include <iostream>
 
std::string middleThreeDigits(int n)
Line 1,138 ⟶ 1,832:
}
}
</syntaxhighlight>
</lang>
{{out}}
<pre>middleThreeDigits(123): 123
Line 1,157 ⟶ 1,851:
middleThreeDigits(-2002): even number of digits
middleThreeDigits(0): less than three digits</pre>
 
=={{header|C_sharp|C#}}==
<syntaxhighlight lang="csharp">using System;
 
namespace RosettaCode
{
class Program
{
static void Main(string[] args)
{
string text = Math.Abs(int.Parse(Console.ReadLine())).ToString();
Console.WriteLine(text.Length < 2 || text.Length % 2 == 0 ? "Error" : text.Substring((text.Length - 3) / 2, 3));
}
}
}</syntaxhighlight>
{{out}}
<pre>123:123
12345:234
1234567:345
987654321:654
10001:000
-10001:000
-123:123
-100:100
100:100
-12345:234
 
1:Error
2:Error
-1:Error
-10:Error
2002:Error
-2002:Error
0:Error
</pre>
 
=={{header|Clojure}}==
<syntaxhighlight lang="clojure">(defn middle3
<lang Clojure>
(defn middle3 [v]
(let [nodigit-str (str (Math/abs v))
digitslen (strcount nodigit-str)]
len (count digits)]
(cond
(< len 3) :too_shorttoo-short
(even? len) :no_middle_in_even_no_of_digitseven-digit-count
:else (let [midhalf (/ len 2)]
(subs digit-str (- half start1) (-+ midhalf 2)])))))
(apply str
(take 3
(nthnext digits start)))))))
 
(clojure.pprint/print-table
(def passes '(123 12345 1234567 987654321 10001 -10001 -123 -100 100 -12345))
(for [i [123 12345 1234567 987654321 10001 -10001 -123 -100 100 -12345
(def fails '(1 2 -1 -10 2002 -2002 0))
1 2 -1 -10 2002 -2002 0]]
 
{:i i :middle-3 (middle3 i)}))
</lang>
</syntaxhighlight>
 
{{out}}
<pre>
| :i | :middle-3 |
user=> (map middle3 passes)
|-----------+-------------------|
("123" "234" "345" "654" "000" "000" "123" "100" "100" "234")
| 123 | 123 |
user=> (map middle3 fails)
| 12345 | 234 |
(:too_short :too_short :too_short :too_short :no_middle_in_even_no_of_digits :no_middle_in_even_no_of_digits :too_short)
| 1234567 | 345 |
| 987654321 | 654 |
| 10001 | 000 |
| -10001 | 000 |
| -123 | 123 |
| -100 | 100 |
| 100 | 100 |
| -12345 | 234 |
| 1 | :too-short |
| 2 | :too-short |
| -1 | :too-short |
| -10 | :too-short |
| 2002 | :even-digit-count |
| -2002 | :even-digit-count |
| 0 | :too-short |
</pre>
 
=={{header|CLU}}==
<syntaxhighlight lang="clu">middle_three_digits = proc (n: int) returns (string)
signals (too_small, even_length)
s: string := int$unparse(int$abs(n))
if string$size(s) < 3 then signal too_small end
if string$size(s) // 2 = 0 then signal even_length end
return(string$substr(s, string$size(s)/2, 3))
end middle_three_digits
 
start_up = proc ()
po: stream := stream$primary_output()
tests: sequence[int] := sequence[int]$
[123,12345,1234567,987654321,10001,-10001,-123,-100,100,-12345,
1,2,-1,-10,2002,-2002,0]
for test: int in sequence[int]$elements(tests) do
stream$putright(po, int$unparse(test) || ": ", 11)
stream$putl(po, middle_three_digits(test))
except
when too_small: stream$putl(po, "Too small")
when even_length: stream$putl(po, "Even length")
end
end
end start_up</syntaxhighlight>
{{out}}
<pre> 123: 123
12345: 234
1234567: 345
987654321: 654
10001: 000
-10001: 000
-123: 123
-100: 100
100: 100
-12345: 234
1: Too small
2: Too small
-1: Too small
-10: Too small
2002: Even length
-2002: Even length
0: Too small</pre>
 
=={{header|COBOL}}==
<langsyntaxhighlight COBOLlang="cobol">identification division.
program-id. middle3.
environment division.
Line 1,277 ⟶ 2,062:
add 1 to digit-counter
end-perform.
exit paragraph.</langsyntaxhighlight>
Output
<pre> 123 --> 123
Line 1,297 ⟶ 2,082:
0 --> Number too small</pre>
Optimised version
<langsyntaxhighlight lang="cobol">identification division.
program-id. middle3.
environment division.
Line 1,369 ⟶ 2,154:
end-if.
 
</syntaxhighlight>
</lang>
Output
<pre> 123 --> 123
Line 1,391 ⟶ 2,176:
 
=={{header|Common Lisp}}==
===Solution #1===
<lang lisp>
<syntaxhighlight lang="lisp">
(defun mid3 (n)
(let ((a (abs n))
Line 1,404 ⟶ 2,190:
((evenp hmd) (need "odd number of"))
(t (nbr (mod (truncate a (expt 10 (/ (- hmd 3) 2))) 1000)))))))
</syntaxhighlight>
</lang>
 
Test code:
 
<langsyntaxhighlight lang="lisp">
(loop as n in '(123 12345 1234567 987654321
10001 -10001 -123 -100 100 -12345
1 2 -1 -10 2002 -2002 0)
do (format t "~d:~12t~a~%" n (mid3 n)))
</syntaxhighlight>
</lang>
{{out}}
<pre>123: 123
Line 1,432 ⟶ 2,218:
-2002: Need odd number of digits, not 4.
0: Zero is 1 digit</pre>
 
===Solution #2===
<syntaxhighlight lang="lisp">
(defun mid3 (i)
(let ((ch-vec (coerce (format nil "~A" (abs i)) 'vector)))
(when (evenp (length ch-vec))
(return-from mid3
(format nil "Error: The number representation must have an odd ~
number of digits.")))
 
(when (and (< i 100)
(> i -100))
(return-from mid3
(format nil "Error: Must be >= 100 or <= -100.")))
(let ((half (/ (1- (length ch-vec)) 2)))
(return-from mid3 (format nil "~A~A~A"
(elt ch-vec (1- half))
(elt ch-vec half)
(elt ch-vec (1+ half))))
)))
</syntaxhighlight>
 
Test code:
 
<syntaxhighlight lang="lisp">
(defun test-mid3 ()
(let ((test-lst (list 123
12345
1234567
987654321
10001
-10001
-123
-100
100
-12345
1
2
-1
-10
2002
-2002
0
)))
(labels
((run-tests (lst)
(cond ((null lst)
nil)
 
(t
(format t "~A ~15T ~A~%" (first lst) (mid3 (first lst)))
(run-tests (rest lst))))))
 
(run-tests test-lst)))
(values)
)
</syntaxhighlight>
{{out}}
<pre>
123 123
12345 234
1234567 345
987654321 654
10001 000
-10001 000
-123 123
-100 100
100 100
-12345 234
1 Error: Must be >= 100 or <= -100.
2 Error: Must be >= 100 or <= -100.
-1 Error: Must be >= 100 or <= -100.
-10 Error: The number representation must have an odd number of digits.
2002 Error: The number representation must have an odd number of digits.
-2002 Error: The number representation must have an odd number of digits.
0 Error: Must be >= 100 or <= -100.
</pre>
 
=={{header|D}}==
<langsyntaxhighlight lang="d">import std.stdio, std.traits, std.conv;
 
string middleThreeDigits(T)(in T n) pure nothrow if (isIntegral!T) {
Line 1,454 ⟶ 2,317:
foreach (immutable n; failing)
writefln("middleThreeDigits(%s): %s", n, middleThreeDigits(n));
}</langsyntaxhighlight>
{{out}}
<pre>middleThreeDigits(123): 123
Line 1,480 ⟶ 2,343:
===Alternative Version===
This longer version gives a stronger typed output, and it tries to be faster avoiding conversions to string.
<langsyntaxhighlight lang="d">import std.stdio, std.traits, std.math, std.variant;
 
/// Returns a string with the error, or the three digits.
Line 1,566 ⟶ 2,429:
writefln("middleThreeDigits(cast(short)%d): %s", n, mtd);
}
}</langsyntaxhighlight>
{{out}}
<pre>middleThreeDigits(123): 123
Line 1,617 ⟶ 2,480:
 
=={{header|Dart}}==
<syntaxhighlight lang="text">
import'dart:math';
int length(int x)
Line 1,664 ⟶ 2,527:
}
}
</syntaxhighlight>
</lang>
 
=={{header|DCL}}==
<syntaxhighlight lang="text">$ list = "123,12345,1234567,987654321,10001,-10001,-123,-100,100,-12345,1,2,-1,-10,2002,-2002,0"
$ i = 0
$ loop:
Line 1,680 ⟶ 2,544:
$ endif
$ i = i + 1
$ goto loop</langsyntaxhighlight>
{{out}}
<pre>$ @middle_three_digits
Line 1,700 ⟶ 2,564:
-2002: has no middle three
0: has no middle three</pre>
 
=={{header|Delphi}}==
See [https://rosettacode.org/wiki/Middle_three_digits#Pascal Pascal].
 
=={{header|EasyLang}}==
<syntaxhighlight lang="easylang">
func$ midThreeDigits num .
trueNumber$ = abs num
if (len trueNumber$ < 3) or (len trueNumber$ mod 2 = 0)
r$ = "error"
else
r$ = substr trueNumber$ ((len trueNumber$ - 3) / 2 + 1) 3
.
return r$
.
numbers[] = [ 123 12345 1234567 987654321 10001 -10001 -123 -100 100 -12345 1 2 -1 -10 2002 -2002 0 ]
for i in numbers[]
print midThreeDigits i
.
</syntaxhighlight>
{{out}}
<pre>
123
234
345
654
000
000
123
100
100
234
error
error
error
error
error
error
error
</pre>
 
=={{header|Eiffel}}==
<syntaxhighlight lang="eiffel">
<lang Eiffel>
class
APPLICATION
Line 1,764 ⟶ 2,668:
 
end
</syntaxhighlight>
</lang>
{{out}}
<pre>
Line 1,786 ⟶ 2,690:
 
</pre>
 
=={{header|Elena}}==
ELENA 36.4x :
<langsyntaxhighlight lang="elena">import system'routines.;
import extensions.;
middleThreeDigits(int n)
{
[
literalstring s := n absolute.Absolute.toString(); toLiteral.
int len := s length.Length;
if(len<3)
[{
InvalidArgumentException .new:("n must have 3 digits or more"; ).raise()
];}
else if(len .isEven())
[{
InvalidArgumentException .new:("n must have an odd number of digits"; ).raise()
].};
int mid := len / 2.;
^ s .Substring(mid-1,3).
}
]
public program()
{
[
(new int[]{123, 12345, 1234567, 987654321, 10001, -10001, -123, -100, 100, -12345, 1, 2, -1, -10, 2002, -2002, 0)}
.forEach(::(n)
[ {
console console.printLine("middleThreeDigits(",n,"):",middleThreeDigits(n) |\\ if(on::e)(e message=> e.Message))
] }
}</syntaxhighlight>
]</lang>
{{out}}
<pre>
Line 1,839 ⟶ 2,744:
 
=={{header|Elixir}}==
<langsyntaxhighlight Elixirlang="elixir">defmodule Middle do
def three(num) do
n = num |> abs |> to_string
Line 1,868 ⟶ 2,773:
e -> IO.puts e.message
end
end)</langsyntaxhighlight>
 
{{out}}
Line 1,892 ⟶ 2,797:
 
=={{header|Erlang}}==
<langsyntaxhighlight lang="erlang">%
-module(middle_three_digits).
-export([main/0]).
Line 1,931 ⟶ 2,836:
loop(X,N) when X>0 ->
loop(X-1, N div 10).
</syntaxhighlight>
</lang>
{{out}}
<pre>123
Line 1,954 ⟶ 2,859:
 
=={{header|ERRE}}==
<syntaxhighlight lang="erre">
<lang ERRE>
PROGRAM MIDDLE
 
Line 1,999 ⟶ 2,904:
END FOR
END PROGRAM
</syntaxhighlight>
</lang>
{{out}}
<pre>
Line 2,022 ⟶ 2,927:
 
=={{header|Factor}}==
<syntaxhighlight lang="text">USING: combinators formatting io kernel math math.parser
sequences ;
IN: rosetta-code.middle-three-digits
 
CONSTANT: test-values { 123 12345 1234567 987654321 10001 -10001
-123 -100 100 -12345 11234567 2987654321 -110001 -10 2002 -2002 0 }10001
-123 -100 100 -12345 1 2 -1 -10 2002 -2002 0
}
 
: (middle-three) ( str -- str' ) [ midpoint@ ] keep
[ midpoint@ [ 1 - ] [ 2 + ] bi ] dip[ subseq ] bi ;
: too-short ( -- ) "Number must have at least three digits."
"Number must have at least three digits." print ;
: number-even ( -- ) "Number must have an odd number of digits."
"Number must have an odd number of digits." print ;
print ;
 
: processmiddle-three ( n -- )
abs number>string {
{ [ dup length 3 < ] [ drop too-short ] }
{ [ dup length even? ] [ drop number-even ] }
[ (middle-three) print ]
} cond ;
: main ( -- ) test-values [ dup "%9d : " printf process ] each ;
test-values [ dup "%9d : " printf middle-three ] each ;
 
MAIN: main</langsyntaxhighlight>
{{out}}
<pre>
Line 2,071 ⟶ 2,979:
=={{header|Forth}}==
This is a problem, which is easily solved in Forth. It converts the number to a string and checks it length. If the number does not represent a printable string, it returns an empty string.
<langsyntaxhighlight lang="forth">: middle3 ( n1 -- a n2)
abs s>d <# #s #> dup 2/ 0<> over 1 and 0<> and
if 2/ 1- chars + 3 else drop 0 then
;</langsyntaxhighlight>
 
=={{header|Fortran}}==
Please find compilation instructions along with the output for the examples in the comments at the beginning of the file. This program was produced in an Ubuntu distribution of the GNU/linux system.
<syntaxhighlight lang="fortran">
<lang FORTRAN>
!-*- mode: compilation; default-directory: "/tmp/" -*-
!Compilation started at Sat Jun 1 14:48:41
Line 2,151 ⟶ 3,060:
 
end program MiddleMuddle
</syntaxhighlight>
</lang>
 
=={{header|FreeBASIC}}==
<langsyntaxhighlight lang="freebasic">' FB 1.05.0 Win64
 
Function middleThreeDigits (n As Integer) As String
Line 2,185 ⟶ 3,094:
Print
Print "Press any key to quit"
Sleep</langsyntaxhighlight>
 
{{out}}
Line 2,208 ⟶ 3,117:
0 => Error: does not have 3 middle digits
</pre>
 
 
 
=={{header|FutureBasic}}==
<syntaxhighlight lang="futurebasic">
local fn MiddleThreeDigits( n as NSInteger ) as CFStringRef
CFStringRef testStr, resultStr
NSInteger length, middle
testStr = fn StringWithFormat( @"%ld", n )
testStr = fn StringByReplacingOccurrencesOfString( testStr, @"-", @"" )
length = len(testStr)
if length < 3 then resultStr = fn StringWithFormat( @"%10ld -> Error: Less than three digits.", n ) : exit fn
if length == 3 then resultStr = fn StringWithFormat( @"%10ld -> %@", n, testStr ) : exit fn
length = len(testStr)
if ( length mod 2 == 0 )
resultStr = fn StringWithFormat( @"%10ld -> Error: Even length; needs odd.", n )
else
middle = length / 2
resultStr = fn StringWithFormat( @"%10ld -> %@", n, mid( testStr, middle -1, 3 ) )
end if
end fn = resultStr
 
window 1, @"Middle Three Digits", ( 0, 0, 400, 300 )
 
NSUInteger i, count
CFArrayRef testArr
CFNumberRef tempNum
 
testArr = @[@123,@12345,@1234567,@987654321,@10001,@-10001,¬
@-123,@-100,@100,@-12345,@1,@2,@-1,@-10,@2002,@-2002,@0]
 
count = fn ArrayCount( testArr )
for i = 0 to count - 1
print fn MiddleThreeDigits( fn NumberIntegerValue( testArr[i] ) )
next
 
HandleEvents
</syntaxhighlight>
{{output}}
<pre style="font-size: 13px">
123 -> 123
12345 -> 234
1234567 -> 345
987654321 -> 654
10001 -> 000
-10001 -> 000
-123 -> 123
-100 -> 100
100 -> 100
-12345 -> 234
1 -> Error: Less than three digits.
2 -> Error: Less than three digits.
-1 -> Error: Less than three digits.
-10 -> Error: Less than three digits.
2002 -> Error: Even length; needs odd.
-2002 -> Error: Even length; needs odd.
0 -> Error: Less than three digits.
</pre>
 
 
 
 
 
 
 
=={{header|Gambas}}==
'''[https://gambas-playground.proko.eu/?gist=ed25e84978446d65895ccd909fc092fa Click this link to run this code]'''
<langsyntaxhighlight lang="gambas">Public Sub Main()
Dim iList As Integer[] = [123, 12345, 1234567, 987654321, 10001,
-10001, -123, -100, 100, -12345, 1, 2, -1, -10, 2002, -2002, 0] 'Array of integers to process
Line 2,234 ⟶ 3,208:
Next
 
End</langsyntaxhighlight>
Output:
<pre>
Line 2,259 ⟶ 3,233:
 
File m3.go:
<langsyntaxhighlight lang="go">package m3
 
import (
Line 2,284 ⟶ 3,258:
m := len(s) / 2
return s[m-1 : m+2], nil
}</langsyntaxhighlight>
File m3_test.go:
<langsyntaxhighlight lang="go">package m3_test
 
import (
Line 2,344 ⟶ 3,318:
t.Logf("d(%d) returns %q", tc.i, err)
}
}</langsyntaxhighlight>
{{out}}
Output of go test is normally terse:
Line 2,377 ⟶ 3,351:
 
=={{header|Gosu}}==
<langsyntaxhighlight lang="gosu">var valid = {123, 12345, 1234567, 987654321, 10001, -10001, -123, -100, 100, -12345}
valid.each(\ num ->print(middleThree(num)))
 
Line 2,389 ⟶ 3,363:
var start = (s.length / 2) - 1
return s.substring(start, start + 3)
}</langsyntaxhighlight>
 
{{Output}}
Line 2,412 ⟶ 3,386:
 
=={{header|Groovy}}==
<langsyntaxhighlight lang="groovy">def middleThree(Number number) {
def text = Math.abs(number) as String
assert text.size() >= 3 : "'$number' must be more than 3 numeric digits"
Line 2,419 ⟶ 3,393:
int start = text.size() / 2 - 1
text[start..(start+2)]
}</langsyntaxhighlight>
Test Code:
<langsyntaxhighlight lang="groovy">[123, 12345, 1234567, 987654321, 10001, -10001, -123, -100, 100, -12345, 1, 2, -1, -10, 2002, -2002, 0].each { number ->
def text = (number as String).padLeft(10)
try {
Line 2,428 ⟶ 3,402:
println "$text cannot be converted: $error.message"
}
}</langsyntaxhighlight>
Output:
<pre> 123: 123
Line 2,449 ⟶ 3,423:
 
=={{header|Haskell}}==
<syntaxhighlight lang="haskell">------------------- MIDDLE THREE DIGITS ------------------
<lang haskell>mid3 :: Int -> Either String String
 
mid3 :: Int -> Either String String
mid3 n
| m < 100 = Left "is too small"
| even lng = Left "has an even number of digits"
| otherwise = Right . take 3 $ drop ((lng - 3) `div` 2) s
where
Line 2,459 ⟶ 3,435:
lng = length s
 
-- TEST ------------------------------- TEST -------------------------
main :: IO ()
main = do
Line 2,481 ⟶ 3,457:
, 0
]
w = maximum $ (length . show) <$> xs
(putStrLn . unlines) $
(\n ->
justifyRight w ' ' (show n) ++<>
" -> " ++<> either ((>>= id)concat . ("(" :) . (: [")"])) id (mid3 n)) <$>
xs
 
where
justifyRight :: Int -> Char -> String -> String
justifyRight n c s = (drop (. length s) <*> (replicate n c ++ s<>)</langsyntaxhighlight>
Output:
<pre> 123 -> 123
Line 2,501 ⟶ 3,477:
100 -> 100
-12345 -> 234
1 -> (is too small)
2 -> (is too small)
-1 -> (is too small)
-10 -> (is too small)
2002 -> (has an even number of digits)
-2002 -> (has an even number of digits)
0 -> (is too small)</pre>
 
=={{header|Icon}} and {{header|Unicon}}==
Line 2,513 ⟶ 3,489:
The following solution works in both languages.
 
<langsyntaxhighlight lang="unicon">procedure main(a)
every n := !a do write(right(n,15)," -> ",midM(n))
end
Line 2,524 ⟶ 3,500:
else "wrong number of digits"
else "too short"
end</langsyntaxhighlight>
 
with output:
Line 2,549 ⟶ 3,525:
 
=={{header|J}}==
 
A key issue here is that some numbers do not have a "middle 3 digits" -- either because the number is too short, or because it has an even number of digits (or both, two digit numbers).
 
'''Solution:'''
<langsyntaxhighlight lang="j">asString=: ":"0 NB. convert vals to strings
getPfxSize=: [: -:@| 3 -~ # NB. get size of prefix to drop before the 3 middle digits
getMid3=: (3 {. getPfxSize }. ,&'err') :: ('err'"_) NB. get 3 middle digits or return 'err'
getMiddle3=: getMid3@asString@:|</langsyntaxhighlight>
'''Example:'''
<langsyntaxhighlight lang="j"> vals=: 123 12345 1234567 987654321 10001 _10001 _123 _100 100 _12345 1 2 _1 _10 2002 _2002 0
getMiddle3 vals
123
Line 2,573 ⟶ 3,552:
err
err
err</langsyntaxhighlight>
 
Or, expressed more concisely:<syntaxhighlight lang="j"> ({~ 2 1 0 -~ -:@>:@#) ::('err'"_)@":@| vals
123
234
345
654
000
000
123
100
100
234
err
err
err
err
err
err
err</syntaxhighlight>
 
=={{header|Java}}==
<langsyntaxhighlight Javalang="java">public class MiddleThreeDigits {
 
public static void main(String[] args) {
Line 2,602 ⟶ 3,600:
return s.substring(mid - 1, mid + 2);
}
}</langsyntaxhighlight>
<pre>middleThreeDigits(123): 123
middleThreeDigits(12345): 234
Line 2,626 ⟶ 3,624:
 
=={{header|JavaScript}}==
<langsyntaxhighlight JavaScriptlang="javascript">function middleThree(x){
var n=''+Math.abs(x); var l=n.length-1;
if(l<2||l%2) throw new Error(x+': Invalid length '+(l+1));
Line 2,635 ⟶ 3,633:
1, 2, -1, -10, 2002, -2002, 0].forEach(function(n){
try{console.log(n,middleThree(n))}catch(e){console.error(e.message)}
});</langsyntaxhighlight>
 
<pre>123 "123"
Line 2,658 ⟶ 3,656:
Or, using an option type, composing a solution from existing generic primitives, and formatting the output a little:
{{Trans|Python}}
<langsyntaxhighlight lang="javascript">(() => {
'use strict';
 
Line 2,783 ⟶ 3,781:
// MAIN ---
return main();
})();</langsyntaxhighlight>
{{Out}}
<pre>
Line 2,805 ⟶ 3,803:
 
=={{header|jq}}==
<langsyntaxhighlight lang="jq">def middle3:
if . < 0 then -. else . end
| tostring as $s
Line 2,814 ⟶ 3,812:
 
(123, 12345, 1234567, 987654321, 10001, -10001, -123, -100, 100, -12345, 1, 2, -1, -10, 2002, -2002, 0)
| "\(.) => \( .|middle3 )"</langsyntaxhighlight>
Typescript:<langsyntaxhighlight lang="sh"> $ jq -r -n -f Middle_three_digits.jq
123 => 123
12345 => 234
Line 2,832 ⟶ 3,830:
2002 => invalid length: 4
-2002 => invalid length: 4
0 => invalid length: 1 </langsyntaxhighlight>
 
=={{header|Julia}}==
{{works with|Julia|1.0.3}}
 
<syntaxhighlight lang="julia">using Printf
<lang julia>function middle3(n::Integer)
 
function middle3(n::Integer)
l = ndigits(n)
iseven(l) && error("n must have an odd number of digits")
Line 2,847 ⟶ 3,848:
-100, 100, -12345, 1, 2, -1, -10, 2002, -2002, 0]
@printf("%10d -> %s\n", n, try middle3(n) catch e e.msg end)
end</langsyntaxhighlight>
 
{{out}}
Line 2,869 ⟶ 3,870:
 
=={{header|K}}==
<syntaxhighlight lang="k">
<lang K>
/ Rosetta code - Middle three digits
/ mid3.k
mid3: {qs:$x;:[qs[0]="-";qs: 1 _ qs];:[(#qs)<3;:"small";(1+#qs)!2;:"even"];p:(-3+#qs)%2;:(|p _|p _ qs)}
</syntaxhighlight>
</lang>
The output of the session:
{{out}}
Line 2,901 ⟶ 3,902:
"small")
</pre>
 
=={{header|Klingphix}}==
<syntaxhighlight lang="klingphix">include ..\Utilitys.tlhy
 
( 123 12345 1234567 987654321 10001 -10001 -123 -100 100 -12345 1 2 -1 -10 2002 -2002 0 )
 
len [
get ( dup " : " ) lprint
abs tostr len >ps
tps 3 < ( ["too short" ?]
[ tps 2 mod ( [tps 2 / 3 slice ?] ["is even" ?] ) if]
) if
ps> drop drop
] for
 
" " input
</syntaxhighlight>
{{out}}
<pre>123 : 123
12345 : 234
1234567 : 345
987654321 : 654
10001 : 000
-10001 : 000
-123 : 123
-100 : 100
100 : 100
-12345 : 234
1 : too short
2 : too short
-1 : too short
-10 : too short
2002 : is even
-2002 : is even
0 : too short</pre>
 
=={{header|Klong}}==
<langsyntaxhighlight lang="k">items::[123 12345 1234567 987654321 10001 -10001 -123 -100 100 -12345 1 2 -1 -10 2002 -2002 0]
 
mid3::{[d k];:[3>k::#$#x;"small":|0=k!2;"even";(-d)_(d::_(k%2)-1)_$#x]}
.p(mid3'items)</langsyntaxhighlight>
Output:
<pre>[123 234 345 654 000 000 123 100 100 234 small small small small even even small]</pre>
 
=={{header|Kotlin}}==
<langsyntaxhighlight lang="scala">fun middleThree(x: Int): Int? {
val s = Math.abs(x).toString()
return when {
Line 2,926 ⟶ 3,962:
println(middleThree(123))// 123
println(middleThree(123555)) //null
}</langsyntaxhighlight>
 
=={{header|Lambdatalk}}==
<syntaxhighlight lang="scheme">
{def S 123 12345 1234567 987654321 10001 -10001 -123 -100 100 -12345
1 2 -1 -10 2002 -2002 0}
-> S
 
{def middle3digits
{lambda {:w}
{let { {:w {abs :w}}
{:l {W.length {abs :w}}}
} {if {= {% :l 2} 0}
then has an even number of digits
else {if {< :l 3}
then has not enough digits
else {W.get {- {/ :l 2} 1} :w}
{W.get {/ :l 2} :w}
{W.get {+ {/ :l 2} 1} :w} }}}}}
-> middle3digits
 
 
{table
{S.map {lambda {:i}
{tr {td {@ style="text-align:right;"}:i:}
{td {middle3digits :i}}}}
{S}} }
->
123: 123
12345: 234
1234567: 345
987654321: 654
10001: 000
-10001: 000
-123: 123
-100: 100
100: 100
-12345: 234
1: has not enough digits
2: has not enough digits
-1: has not enough digits
-10: has an even number of digits
2002: has an even number of digits
-2002: has an even number of digits
0: has not enough digits
</syntaxhighlight>
 
=={{header|Lasso}}==
<langsyntaxhighlight Lassolang="lasso">define middlethree(value::integer) => {
local(
pos_value = math_abs(#value),
Line 2,950 ⟶ 4,031:
'<br />'
^}
'</pre>'</langsyntaxhighlight>
'''Output'''
<pre> 123: 123
Line 2,971 ⟶ 4,052:
 
=={{header|Logo}}==
<langsyntaxhighlight lang="logo">to middle3digits :n
if [less? :n 0] [make "n minus :n]
local "len make "len count :n
Line 2,989 ⟶ 4,070:
]
 
bye</langsyntaxhighlight>
 
{{Output}}
Line 3,011 ⟶ 4,092:
 
=={{header|Lua}}==
<langsyntaxhighlight lang="lua">function middle_three(n)
if n < 0 then
n = -n
Line 3,036 ⟶ 4,117:
print(n, middle_three(n))
end
end</langsyntaxhighlight>
 
{{out}}
Line 3,058 ⟶ 4,139:
 
=={{header|Maple}}==
<langsyntaxhighlight lang="maple">middleDigits := proc(n)
local nList, start;
nList := [seq(parse(i), i in convert (abs(n), string))];
Line 3,076 ⟶ 4,157:
middleDigits(i);
printf("\n");
end do;</langsyntaxhighlight>
{{out}}
<pre>
Line 3,098 ⟶ 4,179:
</pre>
 
=={{header|Mathematica}}/{{header|Wolfram Language}}==
<langsyntaxhighlight Mathematicalang="mathematica">middleThree[n_Integer] :=
Block[{digits = IntegerDigits[n], len},
len = Length[digits];
Line 3,109 ⟶ 4,190:
100, -12345, 1, 2, -1, -10, 2002, -2002, 0};
 
Column[middleThree /@ testData]</langsyntaxhighlight>
{{out}}<pre>123
123
234
345
Line 3,127 ⟶ 4,207:
err: even number of digits
err: even number of digits
err: n too small</pre>
</pre>
 
=={{header|MATLAB}} / {{header|Octave}}==
<langsyntaxhighlight MATLABlang="matlab">function s=middle_three_digits(a)
% http://rosettacode.org/wiki/Middle_three_digits
 
Line 3,145 ⟶ 4,224:
end;
 
s = s((length(s)+1)/2+[-1:1]);</langsyntaxhighlight>
Test with
<langsyntaxhighlight MATLABlang="matlab"> x=[123, 12345, 1234567, 987654321, 10001, -10001, -123, -100, 100, -12345, 1, 2, -1, -10, 2002, -2002, 0];
for k=1:length(x); fprintf(1,'%9i:%s\n',x(k),middle_three_digits(x(k)));end;</langsyntaxhighlight>
Result
<pre>
Line 3,169 ⟶ 4,248:
0:*** error: number of digits must not be smaller than 3 ***
</pre>
 
=={{header|MiniScript}}==
<syntaxhighlight lang="miniscript">middle3 = function(num)
if num < 0 then num = -num
s = str(num)
if s.len < 3 then return "Input too short"
if s.len % 2 == 0 then return "Input length not odd"
mid = (s.len + 1) / 2 - 1
return s[mid-1:mid+2]
end function
 
for test in [123, 12345, 1234567, 987654321, 10001, -10001, -123, -100,
100, -12345, 1, 2, -1, -10, 2002, -2002, 0]
print test + " --> " + middle3(test)
end for</syntaxhighlight>
{{out}}
<pre>123 --> 123
12345 --> 234
1234567 --> 345
987654321 --> 654
10001 --> 000
-10001 --> 000
-123 --> 123
-100 --> 100
100 --> 100
-12345 --> 234
1 --> Input too short
2 --> Input too short
-1 --> Input too short
-10 --> Input too short
2002 --> Input length not odd
-2002 --> Input length not odd
0 --> Input too short</pre>
 
=={{header|МК-61/52}}==
<syntaxhighlight lang="text">П0 lg [x] 3 - x>=0 23 ИП0 1 0
/ [x] ^ lg [x] 10^x П1 / {x} ИП1
* БП 00 1 + x=0 29 ИП0 С/П 0
/</langsyntaxhighlight>
 
''Instruction:'' enter the number in the РX (on display), the result after the execution of the same. In the case of an even or less than 3 number of digits the indicator displays an error message.
Line 3,180 ⟶ 4,292:
=={{header|ML}}==
==={{header|mLite}}===
<langsyntaxhighlight lang="ocaml">
val test_array = ["123","12345","1234567","987654321","10001","~10001","~123","~100","100","~12345","1","2","~1","~10","2002","~2002","0"];
Line 3,205 ⟶ 4,317:
;
map (println o middleThreeDigits) test_array;</langsyntaxhighlight>
Output:
<pre>123 --> 123
Line 3,227 ⟶ 4,339:
=={{header|MUMPS}}==
This sample shows the MUMPS code required to pass the specification.
<langsyntaxhighlight MUMPSlang="mumps">/* MUMPS */
MID3(N) ;
N LEN,N2
Line 3,237 ⟶ 4,349:
 
F I=123,12345,1234567,987654321,10001,-10001,-123,-100,100,-12345,1,2,-1,-10,2002,-2002,0 W !,$J(I,10),": ",$$MID3^MID3(I)
</syntaxhighlight>
</lang>
'''Output:'''
<pre>
Line 3,261 ⟶ 4,373:
=={{header|NetRexx}}==
This sample goes the extra mile and provides a method that can display the middle N digits from the input value. To satisfy the requirements of this task, a static invocation of this general method is also provided with the value '''<tt>3</tt>''' hard coded as the digit count.
<langsyntaxhighlight NetRexxlang="netrexx">/* NetRexx */
options replace format comments java crossref symbols nobinary
 
Line 3,307 ⟶ 4,419:
end
return text
</syntaxhighlight>
</lang>
'''Output:'''
<pre>
Line 3,337 ⟶ 4,449:
 
=={{header|NewLISP}}==
<syntaxhighlight lang="newlisp">
<lang NewLISP>
(define (middle3 x)
(if (even? (length x))
Line 3,349 ⟶ 4,461:
 
(map middle3 lst)
</syntaxhighlight>
</lang>
'''Output:'''
<pre>
Line 3,372 ⟶ 4,484:
 
=={{header|Nim}}==
<syntaxhighlight lang="nim">proc middleThreeDigits(i: int): string =
<lang nim>import math
 
proc middleThreeDigits(i): auto =
var s = $abs(i)
if s.len < 3 or s.len mod 2 == 0:
Line 3,380 ⟶ 4,490:
let mid = s.len div 2
return s[mid-1..mid+1]
 
const passing = @[123, 12345, 1234567, 987654321, 10001, -10001, -123, -100, 100, -12345]
const failing = @[1, 2, -1, -10, 2002, -2002, 0]
 
for i in passing & failing:
var answer = try: middleThreeDigits(i)
except ValueError: getCurrentExceptionMsg()
echo "middleThreeDigits(", i, ") returned: ", answer</langsyntaxhighlight>
 
Output:
{{out}}
<pre>middleThreeDigits(123) returned: 123
middleThreeDigits(12345) returned: 234
Line 3,408 ⟶ 4,519:
 
=={{header|Objeck}}==
<langsyntaxhighlight lang="objeck">
class Test {
function : Main(args : String[]) ~ Nil {
Line 3,421 ⟶ 4,532:
}
 
}</langsyntaxhighlight>
 
<pre>
Line 3,445 ⟶ 4,556:
=={{header|OCaml}}==
 
<langsyntaxhighlight lang="ocaml">let even x = (x land 1) <> 1
 
let middle_three_digits x =
Line 3,469 ⟶ 4,580:
print_endline "Should fail:";
List.iter print failing;
;;</langsyntaxhighlight>
 
{{out}}
Line 3,497 ⟶ 4,608:
=={{header|Oforth}}==
 
<langsyntaxhighlight Oforthlang="oforth">: middle3
| s sz |
abs asString dup ->s size ->sz
sz 3 < ifTrue: [ "Too short" println return ]
sz isEven ifTrue: [ "Not odd number of digits" println return ]
sz 3 - 2 / 1+ dup 2 + s extract ;</langsyntaxhighlight>
 
{{out}}
Line 3,521 ⟶ 4,632:
=={{header|PARI/GP}}==
{{works with|PARI/GP|2.6.0}}
<langsyntaxhighlight lang="parigp">middle(n)=my(v=digits(n));if(#v>2&&#v%2,100*v[#v\2]+10*v[#v\2+1]+v[#v\2+2],"no middle 3 digits");
apply(middle,[123, 12345, 1234567, 987654321, 10001, -10001, -123, -100, 100, -12345, 1, 2, -1, -10, 2002, -2002, 0])</langsyntaxhighlight>
Output:
<pre>%1 = [123, 234, 345, 654, 0, 0, 123, 100, 100, 234, "no middle 3 digits", "no middle 3 digits", "no middle 3 digits", "no middle 3 digits", "no middle 3 digits", "no middle 3 digits", "no middle 3 digits"]</pre>
 
If for some reason you want to see the leading digits, you can run
<langsyntaxhighlight lang="parigp">apply(n-> Strprintf("%03d", n), %)</langsyntaxhighlight>
 
For earlier versions <code>digits</code> can be defined as
<langsyntaxhighlight lang="parigp">digits(n)=eval(Vec(Str(n)))</langsyntaxhighlight>
or more efficiently as
<langsyntaxhighlight lang="parigp">digits(n)=Vec(apply(n->n-48,Vectorsmall(Str(n))))</langsyntaxhighlight>
 
=={{header|Pascal}}==
{{works with|Free Pascal}}
<langsyntaxhighlight lang="pascal">program Midl3dig;
{$IFDEF FPC}
{$MODE Delphi} //result /integer => Int32 aka longInt etc..
Line 3,571 ⟶ 4,683:
writeln(n:9,': ',GetMid3dig(Test[i]));
end;
end.</langsyntaxhighlight>
{{out}}
<pre> 123: 123
Line 3,591 ⟶ 4,703:
0: got too few digits
</pre>
 
=={{header|Perl}}==
<langsyntaxhighlight Perllang="perl">#!/usr/bin/perl
use strict ;
use warnings ;
Line 3,617 ⟶ 4,730:
1, 2, -1, -10, 2002, -2002, 0 ) ;
map { middlethree( $_ ) } @numbers ;
</syntaxhighlight>
</lang>
{{out}}
<pre>Middle 3 digits of 123 : 123 !
Line 3,637 ⟶ 4,750:
Middle 3 digits can't be shown : 0 too short!
</pre>
 
=={{header|Perl 6}}==
<lang Perl6>sub middle-three($n) {
given $n.abs {
when .chars < 3 { "$n is too short" }
when .chars %% 2 { "$n has an even number of digits" }
default { "The three middle digits of $n are: ", .substr: (.chars - 3)/2, 3 }
}
}
 
say middle-three($_) for <
123 12345 1234567 987654321 10001 -10001 -123 -100 100 -12345
1 2 -1 -10 2002 -2002 0
>;</lang>
{{out}}
<pre>The three middle digits of 123 are: 123
The three middle digits of 12345 are: 234
The three middle digits of 1234567 are: 345
The three middle digits of 987654321 are: 654
The three middle digits of 10001 are: 000
The three middle digits of -10001 are: 000
The three middle digits of -123 are: 123
The three middle digits of -100 are: 100
The three middle digits of 100 are: 100
The three middle digits of -12345 are: 234
1 is too short
2 is too short
-1 is too short
-10 is too short
2002 has an even number of digits
-2002 has an even number of digits
0 is too short</pre>
 
It is also possible to write a regular expression with a code assertion:
<lang perl6>for [\~] ^10 { say "$_ => $()" if m/^^(\d+) <(\d**3)> (\d+) $$ <?{ $0.chars == $1.chars}> / }</lang>
{{out}}
<pre>01234 => 123
0123456 => 234
012345678 => 345</pre>
 
=={{header|Phix}}==
<!--<syntaxhighlight lang="phix">(phixonline)-->
<lang Phix>procedure mid3(integer i)
<span style="color: #008080;">procedure</span> <span style="color: #000000;">mid3</span><span style="color: #0000FF;">(</span><span style="color: #004080;">integer</span> <span style="color: #000000;">i</span><span style="color: #0000FF;">)</span>
string s = sprintf("%d",abs(i))
<span style="color: #004080;">string</span> <span style="color: #000000;">s</span> <span style="color: #0000FF;">=</span> <span style="color: #7060A8;">sprintf</span><span style="color: #0000FF;">(</span><span style="color: #008000;">"%d"</span><span style="color: #0000FF;">,</span><span style="color: #7060A8;">abs</span><span style="color: #0000FF;">(</span><span style="color: #000000;">i</span><span style="color: #0000FF;">))</span>
integer k = length(s)-3
<span style="color: #004080;">integer</span> <span style="color: #000000;">k</span> <span style="color: #0000FF;">=</span> <span style="color: #7060A8;">length</span><span style="color: #0000FF;">(</span><span style="color: #000000;">s</span><span style="color: #0000FF;">)-</span><span style="color: #000000;">3</span>
printf(1,"%10d: %s\n",{i,iff(k<0 or and_bits(k,1)?"error":s[k/2+1..k/2+3])})
<span style="color: #7060A8;">printf</span><span style="color: #0000FF;">(</span><span style="color: #000000;">1</span><span style="color: #0000FF;">,</span><span style="color: #008000;">"%10d: %s\n"</span><span style="color: #0000FF;">,{</span><span style="color: #000000;">i</span><span style="color: #0000FF;">,</span><span style="color: #008080;">iff</span><span style="color: #0000FF;">(</span><span style="color: #000000;">k</span><span style="color: #0000FF;"><</span><span style="color: #000000;">0</span> <span style="color: #008080;">or</span> <span style="color: #7060A8;">and_bits</span><span style="color: #0000FF;">(</span><span style="color: #000000;">k</span><span style="color: #0000FF;">,</span><span style="color: #000000;">1</span><span style="color: #0000FF;">)?</span><span style="color: #008000;">"error"</span><span style="color: #0000FF;">:</span><span style="color: #000000;">s</span><span style="color: #0000FF;">[</span><span style="color: #000000;">k</span><span style="color: #0000FF;">/</span><span style="color: #000000;">2</span><span style="color: #0000FF;">+</span><span style="color: #000000;">1</span><span style="color: #0000FF;">..</span><span style="color: #000000;">k</span><span style="color: #0000FF;">/</span><span style="color: #000000;">2</span><span style="color: #0000FF;">+</span><span style="color: #000000;">3</span><span style="color: #0000FF;">])})</span>
end procedure
<span style="color: #008080;">end</span> <span style="color: #008080;">procedure</span>
 
constant tests = {123,12345,1234567,987654321,10001,-10001,-123,-100,100,-12345,
<span style="color: #008080;">constant</span> <span style="color: #000000;">tests</span> <span style="color: #0000FF;">=</span> <span style="color: #0000FF;">{</span><span style="color: #000000;">123</span><span style="color: #0000FF;">,</span><span style="color: #000000;">12345</span><span style="color: #0000FF;">,</span><span style="color: #000000;">1234567</span><span style="color: #0000FF;">,</span><span style="color: #000000;">987654321</span><span style="color: #0000FF;">,</span><span style="color: #000000;">10001</span><span style="color: #0000FF;">,-</span><span style="color: #000000;">10001</span><span style="color: #0000FF;">,-</span><span style="color: #000000;">123</span><span style="color: #0000FF;">,-</span><span style="color: #000000;">100</span><span style="color: #0000FF;">,</span><span style="color: #000000;">100</span><span style="color: #0000FF;">,-</span><span style="color: #000000;">12345</span><span style="color: #0000FF;">,</span>
1,2,-1,-10,2002,-2002,0}
<span style="color: #000000;">1</span><span style="color: #0000FF;">,</span><span style="color: #000000;">2</span><span style="color: #0000FF;">,-</span><span style="color: #000000;">1</span><span style="color: #0000FF;">,-</span><span style="color: #000000;">10</span><span style="color: #0000FF;">,</span><span style="color: #000000;">2002</span><span style="color: #0000FF;">,-</span><span style="color: #000000;">2002</span><span style="color: #0000FF;">,</span><span style="color: #000000;">0</span><span style="color: #0000FF;">}</span>
for i=1 to length(tests) do
<span style="color: #008080;">for</span> <span style="color: #000000;">i</span><span style="color: #0000FF;">=</span><span style="color: #000000;">1</span> <span style="color: #008080;">to</span> <span style="color: #7060A8;">length</span><span style="color: #0000FF;">(</span><span style="color: #000000;">tests</span><span style="color: #0000FF;">)</span> <span style="color: #008080;">do</span>
mid3(tests[i])
<span style="color: #000000;">mid3</span><span style="color: #0000FF;">(</span><span style="color: #000000;">tests</span><span style="color: #0000FF;">[</span><span style="color: #000000;">i</span><span style="color: #0000FF;">])</span>
end for</lang>
<span style="color: #008080;">end</span> <span style="color: #008080;">for</span>
<!--</syntaxhighlight>-->
{{out}}
<pre>
Line 3,711 ⟶ 4,787:
 
=={{header|PHP}}==
<langsyntaxhighlight PHPlang="php">// 32-bit builds of PHP: Integers can be from -2147483648 to 2147483647
// 64-bit builds of PHP: Integers can be from -9223372036854775808 to 9223372036854775807
 
Line 3,749 ⟶ 4,825:
{
echo $nums.' : '.middlethree($nums). '<br>';
}</langsyntaxhighlight>
Output:
<pre>123 : 123
Line 3,768 ⟶ 4,844:
-2002 : The value must contain an odd amount of digits...
0 : The value must contain at least three digits...</pre>
 
=={{header|Picat}}==
===Prolog-style===
{{trans|Prolog}}
<syntaxhighlight lang="picat">get_middle_f1(Str) = [X,Y,Z] =>
append(Pre,[X,Y,Z],Post,Str),
length(Pre) = length(Post).</syntaxhighlight>
 
===List slice===
<syntaxhighlight lang="picat">get_middle_f2(Str) = Str[Mid-1..Mid+1] =>
Mid = 1 + Str.len div 2.</syntaxhighlight>
 
===Test===
<syntaxhighlight lang="picat">go =>
Success = [123, 12345, 1234567, 987654321, 10001, -10001, -123, -100, 100, -12345],
Fail = [1, 2, -1, -10, 2002, -2002, 0],
All = Success ++ Fail,
 
test(All, get_middle_f1),
test(All, get_middle_f2).
 
% Test and check for exceptions
test(List,F) =>
printf("\nTesting %w:\n", F),
foreach(N in List)
catch(Middle=apply(get_middle,N,F), E, printf("%d = exception %w\n",N,E)),
if E.var() then
println([n=N,middle=Middle])
end
end,
nl.
 
% Check with the get_middle funcion F
get_middle(N,F) = apply(F,Str) =>
Str = N.abs().to_string(),
Len = length(Str),
if Len mod 2 = 0 then throw $not_odd_length(N)
elseif Len < 3 then throw $number_too_small(N)
end.</syntaxhighlight>
 
{{out}}
<pre>[n = 123,middle = 123]
[n = 12345,middle = 234]
[n = 1234567,middle = 345]
[n = 987654321,middle = 654]
[n = 10001,middle = 000]
[n = -10001,middle = 000]
[n = -123,middle = 123]
[n = -100,middle = 100]
[n = 100,middle = 100]
[n = -12345,middle = 234]
[n = 1,exception = number_too_small(1)]
[n = 2,exception = number_too_small(2)]
[n = -1,exception = number_too_small(-1)]
[n = -10,exception = not_odd_length(-10)]
[n = 2002,exception = not_odd_length(2002)]
[n = -2002,exception = not_odd_length(-2002)]
[n = 0,exception = number_too_small(0)]</pre>
 
=={{header|PicoLisp}}==
<langsyntaxhighlight PicoLisplang="picolisp">(de middle3digits (N)
(let (Lst (chop (abs N)) Len (length Lst))
(tab (10 -2 -30)
Line 3,779 ⟶ 4,913:
((bit? 1 Len)
(head 3 (nth Lst (/ Len 2))) )
(T "even number of digits") ) ) ) )</langsyntaxhighlight>
Test:
<langsyntaxhighlight PicoLisplang="picolisp">(mapc middle3digits
(123 12345 1234567 987654321 10001 -10001 -123 -100 100 -12345
1 2 -1 -10 2002 -2002 0 ) )</langsyntaxhighlight>
Output:
<pre> 123: 123
Line 3,802 ⟶ 4,936:
-2002: even number of digits
0: not enough digits</pre>
 
=={{header|Pike}}==
{{trans|PHP}}
 
<syntaxhighlight lang="pike">string middlethree(int i) {
i = abs(i);
int length = sizeof((string)i);
if(length >= 3) {
if(length % 2 == 1) {
int middle = (int)floor(length / 2) - 1;
return(((string)i)[middle..middle+2]);
}
else {
return "The value must contain an odd amount of digits...";
}
}
else {
return "The value must contain at least three digits...";
}
}
 
int main() {
array(int) numbers = ({123, 12345, 1234567, 987654321, 10001, -10001, -123, -100, 100, -12345, 1, 2, -1, -10, 2002, -2002, 0});
 
foreach(numbers, int nums) {
write((string)nums + " : " + middlethree(nums) + "\n");
}
return 0;
}</syntaxhighlight>
{{out}}
<pre>123 : 123
12345 : 234
1234567 : 345
987654321 : 654
10001 : 000
-10001 : 000
-123 : 123
-100 : 100
100 : 100
-12345 : 234
1 : The value must contain at least three digits...
2 : The value must contain at least three digits...
-1 : The value must contain at least three digits...
-10 : The value must contain at least three digits...
2002 : The value must contain an odd amount of digits...
-2002 : The value must contain an odd amount of digits...
0 : The value must contain at least three digits...</pre>
 
=={{header|PL/I}}==
<syntaxhighlight lang="pl/i">
<lang PL/I>
middle: procedure options (main); /* 29 October 2013 */
declare n fixed (15);
Line 3,829 ⟶ 5,011:
 
end middle;
</syntaxhighlight>
</lang>
Output:
<pre>
Line 3,848 ⟶ 5,030:
-2002 not possible
0 not possible
</pre>
 
=={{header|Plain English}}==
<syntaxhighlight lang="plainenglish">To run:
Start up.
Test 123.
Test 12345.
Test 1234567.
Test 987654321.
Test 10001.
Test -10001.
Test -123.
Test -100.
Test 100.
Test -12345.
Test 1.
Test 2.
Test -1.
Test -10.
Test 2002.
Test -2002.
Test 0.
Wait for the escape key.
Shut down.
 
To get the middle three digits of a number giving a string:
Privatize the number.
De-sign the number.
Convert the number to the string.
If the string's length is less than 3, put "Number has fewer than three digits" into the string; exit.
If the string's length is even, put "Number has no middle" into the string; exit.
Put the string's length divided by 2 into a midpoint number.
Slap a substring on the string.
Put the substring's first plus the midpoint minus 1 into the substring's first.
Put the substring's first plus 2 into the substring's last.
Put the substring into the string.
 
To test a number:
Get the middle three digits of the number giving a string.
Write "" then the number then " -> " then the string on the console.</syntaxhighlight>
{{out}}
<pre>
123 -> 123
12345 -> 234
1234567 -> 345
987654321 -> 654
10001 -> 000
-10001 -> 000
-123 -> 123
-100 -> 100
100 -> 100
-12345 -> 234
1 -> Number has fewer than three digits
2 -> Number has fewer than three digits
-1 -> Number has fewer than three digits
-10 -> Number has fewer than three digits
2002 -> Number has no middle
-2002 -> Number has no middle
0 -> Number has fewer than three digits
</pre>
 
=={{header|PowerShell}}==
<langsyntaxhighlight lang="powershell">function middle3($inp){
 
$str = [Math]::abs($inp)
Line 3,874 ⟶ 5,115:
$sample = 123, 12345, 1234567, 987654321, 10001, -10001, -123, -100, 100, -12345, 1, 2, -1, -10, 2002, -2002, 0
 
foreach ($x in $sample){middle3 $x}</langsyntaxhighlight>
{{Out}}
<pre>123: 123
Line 3,893 ⟶ 5,134:
-2002: [ERROR] even number of digits.
0: [ERROR] too short.</pre>
 
 
=={{header|Prolog}}==
{{works with|SWI-Prolog|6}}
 
<langsyntaxhighlight lang="prolog">
middle_3_digits(Number, [D1,D2,D3]) :-
verify_middle_3_able(Number, Digits),
Line 3,913 ⟶ 5,153:
; true
).
</syntaxhighlight>
</lang>
 
 
Test code:
 
<langsyntaxhighlight lang="prolog">
test_correct :-
TestCases = [123, 12345, 1234567, 987654321, 10001, -10001, -123, -100, 100, -12345],
Line 3,925 ⟶ 5,165:
format('Middle 3 digits of ~w ~30|: ~w~n', [TestCase, Result])
).
</syntaxhighlight>
</lang>
 
 
Line 3,964 ⟶ 5,204:
 
=={{header|Python}}==
===Procedural===
<lang python>>>> def middle_three_digits(i):
<syntaxhighlight lang="python">>>> def middle_three_digits(i):
s = str(abs(i))
length = len(s)
Line 3,998 ⟶ 5,239:
middle_three_digits(-2002) returned: AssertionError('Need odd and >= 3 digits',)
middle_three_digits(0) returned: AssertionError('Need odd and >= 3 digits',)
>>> </langsyntaxhighlight>
 
===Composition of pure functions===
 
Or,Using usinga ancomposable option type as an alternative to error handling:
{{Trans|Haskell}}
<syntaxhighlight lang ="python">from functools'''Middle import3 (reduce)digits'''
 
 
# mid3digits :: Int -> Either String String
def mid3digits(n):
'''Either the middle three digits,
def go(s):
or returnan Right(explanatory string.'''
s[(len(s) - 3) // 2:][0:3]
)
m = abs(n)
s = str(m)
return Left('Less than 3 digits') if (100 > m) else (
Left('Even digit count') if even(len(s)) else goRight(s)
s[(len(s) - 3) // 2:][0:3]
)
)
 
Line 4,021 ⟶ 5,262:
# TEST ----------------------------------------------------
def main():
xs = ['''Test'''
 
123, 12345, 1234567, 987654321, 10001, -10001, -123,
def bracketed(x):
-100, 100, -12345, 1, 2, -1, -10, 2002, -2002, 0
return '(' + str(x) + ')'
]
 
mx = max(map(compose(len)(str), xs))
print(
# = max(len(x) for x in [str(x) for x in xs])
tabulated('Middle three digits, where defined:\n')(str)(
print (
'\n'.join either([bracketed)(str)
)(mid3digits)([
123, 12345, 1234567, 987654321, justifyRight(mx)('10001, ')(str(n)) + '-10001, -> ' + (123,
-100, 100, -12345, 1, 2, -1, -10, 2002, -2002, 0
either(lambda s: '(' + str(s) + ')')(str)(mid3digits(n))
])
) for n in xs
]),
)
 
 
# GENERIC -------------------------------------------------
 
# Left :: a -> Either a b
def Left(x):
'''Constructor for an empty Either (option type) value
with an associated string.'''
return {'type': 'Either', 'Right': None, 'Left': x}
 
 
# Right :: b -> Either a b
def Right(x):
'''Constructor for a populated Either (option type) value'''
return {'type': 'Either', 'Left': None, 'Right': x}
 
 
# compose (<<<) :: (b -> c) -> (a -> b) -> a -> c
def compose(g):
'''Function composition.'''
return lambda f: lambda x: g(f(x))
 
Line 4,048 ⟶ 5,300:
# either :: (a -> c) -> (b -> c) -> Either a b -> c
def either(fl):
'''The application of fl to e if e is a Left value,
or the application of fr to e if e is a Right value.'''
return lambda fr: lambda e: fl(e['Left']) if (
None is e['Right']
Line 4,055 ⟶ 5,309:
# even :: Int -> Bool
def even(x):
'''Is x even ?'''
return 0 == x % 2
 
 
# justifyRighttabulated :: IntString -> Char(b -> String) -> (a -> b) -> [a] -> String
def justifyRighttabulated(ns):
'''Heading -> x display function -> fx display function ->
return lambda cFiller: lambda a: (
f -> value list -> tabular string.'''
((n * cFiller) + str(a))[-n:]
def go(xShow, fxShow, f, xs):
w = max(map(compose(len)(str), xs))
return s + '\n' + '\n'.join(
xShow(x).rjust(w, ' ') + ' -> ' + fxShow(f(x)) for x in xs
)
return lambda xShow: lambda fxShow: lambda f: lambda xs: go(
xShow, fxShow, f, xs
)
 
 
# Left :: a -> Either a b
def Left(x):
return {'type': 'Either', 'Right': None, 'Left': x}
 
 
# Right :: b -> Either a b
def Right(x):
return {'type': 'Either', 'Left': None, 'Right': x}
 
 
if __name__ == '__main__':
main()</langsyntaxhighlight>
{{Out}}
<pre>Middle three digits, where 123 -> 123defined:
 
123 -> 123
12345 -> 234
1234567 -> 345
Line 4,095 ⟶ 5,349:
-2002 -> (Even digit count)
0 -> (Less than 3 digits)</pre>
 
 
=={{header|Quackery}}==
 
<syntaxhighlight lang="quackery"> [ 1 & not ] is even ( n --> b )
 
[ over size -
space swap of
swap join ] is justify ( $ n --> $ )
 
[ abs number$
dup size dup 3 < iff
[ 2drop $ "too few digits" ]
done
dup even iff
[ 2drop $ "even digit count" ]
done
dup 3 = iff
drop done
3 - 2 /
tuck split nip
swap negate split drop ] is middle3 ( n --> $ )
 
' [ 123 12345 1234567
987654321 10001 -10001
-123 -100 100 -12345 1
2 -1 -10 2002 -2002 0 ]
 
witheach
[ dup number$ 9 justify echo$
say " --> "
middle3 echo$ cr ]</syntaxhighlight>
 
{{out}}
 
<pre> 123 --> 123
12345 --> 234
1234567 --> 345
987654321 --> 654
10001 --> 000
-10001 --> 000
-123 --> 123
-100 --> 100
100 --> 100
-12345 --> 234
1 --> too few digits
2 --> too few digits
-1 --> too few digits
-10 --> too few digits
2002 --> even digit count
-2002 --> even digit count
0 --> too few digits</pre>
 
=={{header|Racket}}==
<langsyntaxhighlight lang="scheme">#lang racket
(define (middle x)
(cond
Line 4,110 ⟶ 5,416:
 
(map middle (list 123 12345 1234567 987654321 10001 -10001 -123 -100 100 -12345))
(map middle (list 1 2 -1 -10 2002 -2002 0))</langsyntaxhighlight>
The output:
<langsyntaxhighlight lang="scheme">'("123" "234" "345" "654" "000" "000" "123" "100" "100" "234")
'("error: number too small" "error: number too small" "error: number too small" "error: number too small"
"error: number has even length" "error: number has even length" "error: number too small")</langsyntaxhighlight>
 
=={{header|Raku}}==
(formerly Perl 6)
<syntaxhighlight lang="raku" line>sub middle-three($n) {
given $n.abs {
when .chars < 3 { "$n is too short" }
when .chars %% 2 { "$n has an even number of digits" }
default { "The three middle digits of $n are: ", .substr: (.chars - 3)/2, 3 }
}
}
 
say middle-three($_) for <
123 12345 1234567 987654321 10001 -10001 -123 -100 100 -12345
1 2 -1 -10 2002 -2002 0
>;</syntaxhighlight>
{{out}}
<pre>The three middle digits of 123 are: 123
The three middle digits of 12345 are: 234
The three middle digits of 1234567 are: 345
The three middle digits of 987654321 are: 654
The three middle digits of 10001 are: 000
The three middle digits of -10001 are: 000
The three middle digits of -123 are: 123
The three middle digits of -100 are: 100
The three middle digits of 100 are: 100
The three middle digits of -12345 are: 234
1 is too short
2 is too short
-1 is too short
-10 is too short
2002 has an even number of digits
-2002 has an even number of digits
0 is too short</pre>
 
It is also possible to write a regular expression with a code assertion:
<syntaxhighlight lang="raku" line>for [\~] ^10 { say "$_ => $()" if m/^^(\d+) <(\d**3)> (\d+) $$ <?{ $0.chars == $1.chars}> / }</syntaxhighlight>
{{out}}
<pre>01234 => 123
0123456 => 234
012345678 => 345</pre>
 
=={{header|REXX}}==
===version 1===
<langsyntaxhighlight lang="rexx">/* REXX ***************************************************************
* 03.02.2013 Walter Pachl
* 19.04.2013 mid 3 is now a function returning the middle 3 digits
Line 4,145 ⟶ 5,491:
End
End
Return res</langsyntaxhighlight>
Output:
<pre>
Line 4,174 ⟶ 5,520:
<br><br>This REXX version is limited to numbers whose length is &nbsp; <big>≤</big> &nbsp; 100,000 &nbsp; decimal digits.
<br>(The decimal digits limit is defined via the &nbsp; '''numeric digits''' &nbsp; statement in the first line of the subroutine/procedure.)
<langsyntaxhighlight lang="rexx">/*REXX program returns the three middle digits of a decimal number (or an error msg).*/
n= '123 12345 1234567 987654321 10001 -10001 -123 -100 100 -12345',
'+123 0123 2 -1 -10 2002 -2002 0 abc 1e3 -17e-3 1234567.',
Line 4,189 ⟶ 5,535:
if L<3 then return er "argument is less than three digits."
if L//2==0 then return er "argument isn't an odd number of digits."
return substr(x, (L-3)%2+1, 3)</langsyntaxhighlight>
'''output'''
<pre>
Line 4,219 ⟶ 5,565:
 
=={{header|Ring}}==
<langsyntaxhighlight lang="ring">
n = 1234567
middle(n)
Line 4,230 ⟶ 5,576:
but lennr%2=0 see "Number must have an odd number of digits"
else cnr = substr(string(nr),mnr,3) see cnr + nl ok
</syntaxhighlight>
</lang>
 
=={{header|RPL}}==
Staying in the real world: no number/string conversion, -1 is returned if input is invalid.
{{works with|Halcyon Calc|4.2.7}}
≪ ABS DUP XPON
'''IF''' DUP 2 < OVER 2 MOD OR
'''THEN''' DROP2 -1
'''ELSE''' 2 / 1 - ALOG / IP 1000 MOD
'''END'''
≫ '<span style="color:blue">→M3D</span>' STO
 
≪ { 123 12345 1234567 987654321 10001 -10001 -123 -100 100 -12345 -10 2002}
→ tl
≪ { }
1 tl SIZE '''FOR''' j
tl j GET <span style="color:blue">→M3D</span> +
'''NEXT'''
≫ ≫ EVAL
{{out}}
<pre>
1: { 123 234 345 654 0 0 123 100 100 234 -1 -1 }
</pre>
 
=={{header|Ruby}}==
 
<langsyntaxhighlight lang="ruby">def middle_three_digits(num)
# minus sign doesn't factor into digit count,
# and calling #abs acts as a duck-type assertion
Line 4,247 ⟶ 5,615:
return str[length/2 - 1, 3].to_i
end</langsyntaxhighlight>
 
Testing program:
 
<langsyntaxhighlight lang="ruby">samples = [
123, 12345, 1234567, 987654321, 10001, -10001, -123, -100, 100, -12345,
1, 2, -1, -10, 2002, -2002, 0
Line 4,264 ⟶ 5,632:
puts e
end
end</langsyntaxhighlight>
{{out}}
<pre>
Line 4,287 ⟶ 5,655:
 
=={{header|Rust}}==
<langsyntaxhighlight lang="rust">fn middle_three_digits(x: i32) -> Result<String, String> {
let s: String = x.abs().to_string();
let len = s.len();
Line 4,316 ⟶ 5,684:
print_result(*i);
}
}</langsyntaxhighlight>
 
{{Out}}
Line 4,352 ⟶ 5,720:
course just list the numbers backwards.
</pre>
<langsyntaxhighlight Slang="s-lang">
define m3(i)
{
Line 4,382 ⟶ 5,750:
#endif
1, 2, -1, -10, 2002, -2002, 0 } );
</syntaxhighlight>
</lang>
{{out}}<pre>
" 123: 123"
Line 4,406 ⟶ 5,774:
 
=={{header|Scala}}==
<langsyntaxhighlight lang="scala">/**
* Optionally return the middle three digits of an integer.
*
Line 4,427 ⟶ 5,795:
case Some(v) => "%03d".format(v) // Format the value, force leading zeroes
} mkString("\n")
</syntaxhighlight>
</lang>
{{out}}
<pre>123
Line 4,446 ⟶ 5,814:
No middle three
No middle three
</pre>
 
=={{header|sed}}==
<syntaxhighlight lang="sed">h
s/^[-+]\{0,1\}0*\([1-9]\([0-9][0-9]\)\{1,\}\)$/\1/
t l
s/$/ -> error!/
b
:l
s/.\(.\{3,\}\)./\1/
t l
x
G
s/\n/ -> /</syntaxhighlight>
{{out}}
<pre>
$ printf "%s\n" -12345 -10001 -2002 -123 -100 -10 -1 0 1 2 100 123 2002 10001 12345 1234567 987654321 | sed -f middle_three_digits.sed
-12345 -> 234
-10001 -> 000
-2002 -> error!
-123 -> 123
-100 -> 100
-10 -> error!
-1 -> error!
0 -> error!
1 -> error!
2 -> error!
100 -> 100
123 -> 123
2002 -> error!
10001 -> 000
12345 -> 234
1234567 -> 345
987654321 -> 654
</pre>
 
=={{header|Seed7}}==
<langsyntaxhighlight lang="seed7">$include "seed7_05.s7i";
 
const func string: middle3 (in integer: number) is func
Line 4,472 ⟶ 5,874:
writeln(number <& ": " <& middle3(number));
end for;
end func;</langsyntaxhighlight>
 
{{out}}
Line 4,493 ⟶ 5,895:
-2002: error
0: error
</pre>
 
=={{header|SenseTalk}}==
As a People Oriented Programming language, SenseTalk treats values in a fluid fashion. So although the calls to the middle3Digits handler pass an integer as the parameter, the handler itself treats the value as text, looking for occurrences of the text pattern <digit> in it. Similarly, the variable 'output' is initially set to a number, then becomes a text value when the middle digits are put into it at character position 15.
<syntaxhighlight lang="sensetalk">set inputs to [123, 12345, 1234567, 987654321,
10001, -10001, -123, -100, 100, -12345,
1, 2, -1, -10, 2002, -2002, 0]
 
repeat with each num in inputs
put num into output
put middle3digits of num into character 15 of output -- will autofill with "."s
put output
end repeat
 
to handle middle3digits of number
put every occurrence of <digit> in number into digits
if the number of items in digits is less than 3 then return "Error: too few digits"
if the number of items in digits is an even number then return "Error: even number of digits"
repeat while the number of items in digits is greater than 3
delete the first item of digits
delete the last item of digits
end repeat
return digits joined by empty
end middle3digits
</syntaxhighlight>
{{out}}
<pre>
123...........123
12345.........234
1234567.......345
987654321.....654
10001.........000
-10001........000
-123..........123
-100..........100
100...........100
-12345........234
1.............Error: too few digits
2.............Error: too few digits
-1............Error: too few digits
-10...........Error: too few digits
2002..........Error: even number of digits
-2002.........Error: even number of digits
0.............Error: too few digits
</pre>
 
=={{header|Sidef}}==
{{trans|Perl 6Raku}}
<langsyntaxhighlight lang="ruby">func middle_three(n) {
var l = n.len;
if (l < 3) {
"#{n} is too short"
Line 4,504 ⟶ 5,950:
"#{n} has an even number of digits"
} else {
"The three middle digits of #{n} are: " + n.digits.ftslice((l-3 )/ 2, l/2 + 1).first(3).flip.join
}
}
Line 4,511 ⟶ 5,957:
123 12345 1234567 987654321 10001 -10001 -123 -100 100 -12345
1 2 -1 -10 2002 -2002 0
);
nums.each { say middle_three(_) };</langsyntaxhighlight>
{{out}}
<pre>
Line 4,535 ⟶ 5,981:
 
=={{header|SQL}}==
<langsyntaxhighlight lang="sql">;WITH DATA
AS (SELECT CAST(ABS(NUMBER) AS NVARCHAR(MAX)) charNum,
NUMBER,
Line 4,546 ⟶ 5,992:
END Output,
NUMBER Input
FROM DATA </langsyntaxhighlight>
 
<pre>
Line 4,575 ⟶ 6,021:
</pre>
 
=={{header|Swift}}==
<langsyntaxhighlight lang="swift">var num:Int = \\enter your number here
if num<0{num = -num}
var numArray:[Int]=[]
Line 4,591 ⟶ 6,038:
i=i/2
print("\(numArray[i+1]),\(numArray[i]),\(numArray[i-1])")
}</langsyntaxhighlight>
<pre>
123: 123
Line 4,611 ⟶ 6,058:
0: Invalid Input
</pre>
 
 
=={{header|Tcl}}==
<langsyntaxhighlight lang="tcl">proc middleThree n {
if {$n < 0} {
set n [expr {-$n}]
Line 4,627 ⟶ 6,073:
set idx [expr {$idx / 2}]
string range $n $idx [expr {$idx+2}]
}</langsyntaxhighlight>
Demonstrating:
<langsyntaxhighlight lang="tcl">foreach n {
123 12345 1234567 987654321 10001 -10001 -123 -100 100 -12345
1 2 -1 -10 2002 -2002 0
Line 4,640 ⟶ 6,086:
puts "found for ${n}: $mid"
}
}</langsyntaxhighlight>
{{out}}
<pre>
Line 4,661 ⟶ 6,107:
error for 0: no middle three digits: insufficient digits
</pre>
 
=={{header|TI SR-56}}==
{| class="wikitable"
|+ Texas Instruments SR-56 Program Listing for "Middle three digits"
|-
! Display !! Key !! Display !! Key !! Display !! Key !! Display !! Key
|-
| 00 28 || <nowiki>*|x|</nowiki> || 25 54 || / || 50 || || 75 ||
|-
| 01 33 || STO || 26 02 || 2 || 51 || || 76 ||
|-
| 02 01 || 1 || 27 74 || - || 52 || || 77 ||
|-
| 03 18 || *log || 28 01 || 1 || 53 || || 78 ||
|-
| 04 29 || *Int || 29 53 || ) || 54 || || 79 ||
|-
| 05 20 || *1/x || 30 19 || *10^x || 55 || || 80 ||
|-
| 06 20 || *1/x || 31 94 || = || 56 || || 81 ||
|-
| 07 33 || STO || 32 29 || *Int || 57 || || 82 ||
|-
| 08 02 || 2 || 33 54 || / || 58 || || 83 ||
|-
| 09 54 || / || 34 01 || 1 || 59 || || 84 ||
|-
| 10 02 || 2 || 35 00 || 0 || 60 || || 85 ||
|-
| 11 94 || = || 36 00 || 0 || 61 || || 86 ||
|-
| 12 12 || INV || 37 00 || 0 || 62 || || 87 ||
|-
| 13 29 || *Int || 38 94 || = || 63 || || 88 ||
|-
| 14 74 || - || 39 12 || INV || 64 || || 89 ||
|-
| 15 92 || . || 40 29 || *Int || 65 || || 90 ||
|-
| 16 05 || 5 || 41 64 || * || 66 || || 91 ||
|-
| 17 94 || = || 42 01 || 1 || 67 || || 92 ||
|-
| 18 20 || *1/x || 43 00 || 0 || 68 || || 93 ||
|-
| 19 34 || RCL || 44 00 || 0 || 69 || || 94 ||
|-
| 20 01 || 1 || 45 00 || 0 || 70 || || 95 ||
|-
| 21 54 || / || 46 94 || = || 71 || || 96 ||
|-
| 22 52 || ( || 47 41 || R/S || 72 || || 97 ||
|-
| 23 34 || RCL || 48 || || 73 || || 98 ||
|-
| 24 02 || 2 || 49 || || 74 || || 99 ||
|}
 
Asterisk denotes 2nd function key.
 
{| class="wikitable"
|+ Register allocation
|-
| 0: Unused || 1: Number || 2: Log || 3: Unused || 4: Unused
|-
| 5: Unused || 6: Unused || 7: Unused || 8: Unused || 9: Unused
|}
 
Annotated listing:
<syntaxhighlight lang="text">
*|x| STO 1 // Number := |input|
*log *Int // #Digits - 1
*1/x *1/x // Divide by zero if 1-digit number
STO 2 // Log := #Digits - 1
/ 2 = INV *Int - . 5 = *1/x // Divide by zero if #Digits is even
RCL 1 / ( RCL 2 / 2 - 1 ) *10^x = // Shift appropriately
*Int / 1 0 0 0 = INV *Int * 1 0 0 0 = // Take the middle 3 digits
R/S // End
</syntaxhighlight>
 
'''Usage:'''
 
Enter the number and then press RST R/S. A flashing number indicates an error.
 
{{in}}
 
987654321 RST R/S
 
{{out}}
 
After about two seconds, '''654''' will appear on the screen.
 
{{in}}
 
12345 +/- RST R/S
 
{{out}}
 
After about two seconds, '''234''' will appear on the screen.
 
{{in}}
 
5 RST R/S
 
{{out}}
 
A flashing 9.999999999 99 appears on the screen indicating an error.
 
=={{header|UNIX Shell}}==
Line 4,667 ⟶ 6,220:
{{works with|Z Shell}}
 
<langsyntaxhighlight lang="bash">function middle3digits
{
typeset -i n="${1#-}"
Line 4,689 ⟶ 6,242:
printf "%10d: " $n
middle3digits "$n"
done</langsyntaxhighlight>
 
Output: <pre> 123: 123
Line 4,711 ⟶ 6,264:
=={{header|VBA}}==
 
<syntaxhighlight lang="vb">
<lang vb>
Option Explicit
 
Line 4,733 ⟶ 6,286:
End If
End Function
</syntaxhighlight>
</lang>
{{out}}
<pre>123 Return : 123
Line 4,754 ⟶ 6,307:
 
=={{header|VBScript}}==
<langsyntaxhighlight lang="vb">'http://rosettacode.org/wiki/Middle_three_digits
 
Function mid3n(n)
Line 4,774 ⟶ 6,327:
WScript.StdOut.Write n & ": " & mid3n(n)
WScript.StdOut.WriteLine
Next</langsyntaxhighlight>
{{Out}}
<pre>
Line 4,797 ⟶ 6,350:
 
=={{header|Vedit macro language}}==
<langsyntaxhighlight lang="vedit">do {
#1 = Get_Num("Enter a number, or 0 to stop: ", STATLINE)
Ins_Text("Input: ") Num_Ins(#1, COUNT, 10)
Line 4,825 ⟶ 6,378:
}
Buf_Quit(OK)
Return </langsyntaxhighlight>
 
Output:
Line 4,845 ⟶ 6,398:
Input: -2002 Result: Not odd number of digits!
Input: 0 Result: Too few digits! </pre>
 
=={{header|V (Vlang)}}==
<syntaxhighlight lang="v (vlang)">import math
 
const
(
valid = [123, 12345, 1234567, 987654321, 10001, -10001, -123, -100, 100, -12345]
invalid = [1, 2, -1, -10, 2002, -2002, 0]
)
 
fn main() {
for elem in valid {println(middle(elem))}
for elem in invalid {println(middle(elem))}
}
 
 
fn middle(num int) string {
mut strip := math.abs(num).str()
if strip.len < 3 {return 'Error: $num has less than 3 digits'}
if strip.len % 2 == 0 {return 'Error: $num has an even number of digits'}
start := (strip.len / 2) - 1
return strip.substr(start, start + 3)
}
</syntaxhighlight>
 
{{out}}
<pre>
123
234
345
654
000
000
123
100
100
234
Error: 1 has less than 3 digits
Error: 2 has less than 3 digits
Error: -1 has less than 3 digits
Error: -10 has less than 3 digits
Error: 2002 has an even number of digits
Error: -2002 has an even number of digits
Error: 0 has less than 3 digits
</pre>
 
=={{header|Wart}}==
 
<langsyntaxhighlight lang="wart">def (mid3 n)
withs (digits (with outstring # itoa
(pr abs.n))
Line 4,854 ⟶ 6,452:
mid (int max/2))
if (and odd?.max (max >= 3))
(digits mid-1 mid+2)</langsyntaxhighlight>
 
'''Output'''
Line 4,893 ⟶ 6,491:
(mid3 0)
=> nil</pre>
 
=={{header|Wren}}==
{{libheader|Wren-fmt}}
<syntaxhighlight lang="wren">import "./fmt" for Fmt
 
var middle3 = Fn.new { |n|
if (n < 0) n = -n
var s = "%(n)"
var c = s.count
if (c < 3) return "Minimum is 3 digits, only has %(c)."
if (c%2 == 0) return "Number of digits must be odd, %(c) is even."
if (c == 3) return s
var d = (c - 3)/2
return s[d..d+2]
}
 
var a = [123, 12345, 1234567, 987654321, 10001, -10001, -123, -100, 100, -12345,
1, 2, -1, -10, 2002, -2002, 0]
 
for (e in a) {
Fmt.print("$9d -> $n", e, middle3.call(e))
}</syntaxhighlight>
 
{{out}}
<pre>
123 -> 123
12345 -> 234
1234567 -> 345
987654321 -> 654
10001 -> 000
-10001 -> 000
-123 -> 123
-100 -> 100
100 -> 100
-12345 -> 234
1 -> Minimum is 3 digits, only has 1.
2 -> Minimum is 3 digits, only has 1.
-1 -> Minimum is 3 digits, only has 1.
-10 -> Minimum is 3 digits, only has 2.
2002 -> Number of digits must be odd, 4 is even.
-2002 -> Number of digits must be odd, 4 is even.
0 -> Minimum is 3 digits, only has 1.
</pre>
 
=={{header|XPL0}}==
<langsyntaxhighlight XPL0lang="xpl0">include c:\cxpl\stdlib;
 
func Mid3Digits(I); \Return the middle three digits of I
Line 4,918 ⟶ 6,559:
Text(0, Mid3Digits(Passing(X))); CrLf(0);
];
]</langsyntaxhighlight>
 
{{out}}
Line 4,942 ⟶ 6,583:
 
=={{header|zkl}}==
<langsyntaxhighlight lang="zkl">fcn middle(ns){
ns.apply("toString").apply('-("-"))
.apply(fcn(n){nl:=n.len();
Line 4,950 ⟶ 6,591:
}
middle(T(123,12345,1234567,987654321,10001,-10001,-123,-100,100,-12345)).println()
middle(T(1, 2, -1, -10, 2002, -2002, 0)).println();</langsyntaxhighlight>
{{out}}
<pre>
Anonymous user