Middle three digits: Difference between revisions

m
m (→‎{{header|Phix}}: added syntax colouring the hard way)
imported>Arakov
 
(40 intermediate revisions by 24 users not shown)
Line 17:
{{trans|Python}}
 
<langsyntaxhighlight 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’)
Line 29:
print(‘middle_three_digits(#.) returned: #.’.format(x, answer))
X.catch AssertionError error
print(‘middle_three_digits(#.) returned error: ’.format(x)‘’String(error))</langsyntaxhighlight>
 
{{out}}
Line 50:
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 96 ⟶ 166:
end loop;
 
end Middle_Three_Digits;</langsyntaxhighlight>
 
{{out}}
Line 118 ⟶ 188:
 
=={{header|Aime}}==
<langsyntaxhighlight lang="aime">void
m3(integer i)
{
Line 158 ⟶ 228:
 
return 0;
}</langsyntaxhighlight>
{{out}}
<pre> 123: 123
Line 180 ⟶ 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 242 ⟶ 312:
print( ( newline ) )
OD
)</langsyntaxhighlight>
{{out}}
<pre>
Line 265 ⟶ 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 312 ⟶ 382:
end for_n
 
end.</langsyntaxhighlight>
{{out}}
<pre>
Line 332 ⟶ 402:
-2002: Number must have an odd number of digits
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>
 
Line 338 ⟶ 558:
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.
 
<langsyntaxhighlight lang="applescript">on middle3Digits(n)
try
n as number -- Errors if n isn't a number or coercible thereto.
Line 372 ⟶ 592:
set output to output as text
set AppleScript's text item delimiters to astid
return output</langsyntaxhighlight>
 
{{output}}
<langsyntaxhighlight 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.
Line 392 ⟶ 612:
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."</langsyntaxhighlight>
 
===Functional===
<langsyntaxhighlight lang="applescript">-------------------- MID THREE DIGITS ---------------------
 
-- mid3digits :: Int -> Either String String
Line 685 ⟶ 905:
end tell
end if
end zipWith</langsyntaxhighlight>
{{Out}}
<pre>Mid three digits:
Line 708 ⟶ 928:
=={{header|Arturo}}==
 
<langsyntaxhighlight lang="rebol">middleThree: function [num][
n: to :string abs num
if 3 > size n -> return "Number must have at least three digits"
Line 724 ⟶ 944:
loop samples 's [
print [pad to :string s 10 ":" middleThree s]
]</langsyntaxhighlight>
 
{{out}}
Line 747 ⟶ 967:
 
=={{header|ATS}}==
<syntaxhighlight lang="ats">
<lang ATS>
(* ****** ****** *)
//
Line 868 ⟶ 1,088:
 
(* ****** ****** *)
</syntaxhighlight>
</lang>
{{out}}
<pre>Middle-three-digits(123): 123
Line 889 ⟶ 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 901 ⟶ 1,121:
log := log . A_LoopField . "`t: " . SubStr(n,((d-3)//2)+1,3) . "`n"
}
MsgBox % log</langsyntaxhighlight>
{{out}}
<pre>123 : 123
Line 922 ⟶ 1,142:
 
=={{header|AWK}}==
<langsyntaxhighlight AWKlang="awk">#!/bin/awk -f
# use as: awk -f middle_three_digits.awk
 
Line 950 ⟶ 1,170:
}
}
</syntaxhighlight>
</lang>
{{out}}
<pre>
Line 974 ⟶ 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 996 ⟶ 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 1,017 ⟶ 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 1,039 ⟶ 1,286:
OTHERWISE
= MID$(n$, LEN n$ / 2, 3)
ENDCASE</langsyntaxhighlight>
{{out}}
<pre> 123 -> 123
Line 1,060 ⟶ 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 1,104 ⟶ 1,351:
RETURN m
END IF
END FUNCTION</langsyntaxhighlight>
Output
<pre> 123 --> 123
Line 1,127 ⟶ 1,374:
 
==={{header|IS-BASIC}}===
<langsyntaxhighlight ISlang="is-BASICbasic">100 INPUT PROMPT "Number: ":N
120 PRINT MIDDLE$(N)
130 DEF MIDDLE$(N)
Line 1,135 ⟶ 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 1,166 ⟶ 1,413:
Print(#crlf$ + #crlf$ + "Press ENTER to exit"): Input()
CloseConsole()
EndIf</langsyntaxhighlight>
Sample output:
<pre> 123 : 123
Line 1,187 ⟶ 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 1,199 ⟶ 1,446:
end if
wend
end</langsyntaxhighlight>
<pre>123 123
234 12345
Line 1,217 ⟶ 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 1,264 ⟶ 1,544:
)
goto :EOF
%==/The Procedure ==%</langsyntaxhighlight>
{{Out}}
<pre>123: 123
Line 1,289 ⟶ 1,569:
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 1,296 ⟶ 1,576:
2^,+55_,#!>#:<
>/>\#<$#-:#1_v
>_@#<,+55,,,$<</langsyntaxhighlight>
 
{{out}} (multiple runs)
Line 1,335 ⟶ 1,615:
 
=={{header|Bracmat}}==
<langsyntaxhighlight lang="bracmat">( ( middle3
= x p
. @(!arg:? [?p:? [(1/2*!p+-3/2) %?x [(1/2*!p+3/2) ?)
Line 1,350 ⟶ 1,630:
&
);
</syntaxhighlight>
</lang>
Output:
<pre>123
Line 1,372 ⟶ 1,652:
=={{header|Burlesque}}==
 
<langsyntaxhighlight lang="blsq">
blsq ) {123 12345 1234567 987654321 -10001 -123}{XX{~-}{L[3.>}w!m]\[}m[uN
123
Line 1,380 ⟶ 1,660:
000
123
</syntaxhighlight>
</lang>
 
<tt>m]\[</tt> and <tt>uN</tt> are just for displaying it nicely.
Line 1,386 ⟶ 1,666:
=={{header|C}}==
This code is followed by its output.
<syntaxhighlight lang="c">
<lang c>
#include <stdio.h>
#include <stdlib.h>
Line 1,418 ⟶ 1,698:
}
return 0;
}</langsyntaxhighlight>
 
<pre>
Line 1,442 ⟶ 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,498 ⟶ 1,778:
}
}</langsyntaxhighlight>
 
{{out}}
Line 1,525 ⟶ 1,805:
 
=={{header|C++}}==
<langsyntaxhighlight lang="cpp">#include <iostream>
 
std::string middleThreeDigits(int n)
Line 1,552 ⟶ 1,832:
}
}
</syntaxhighlight>
</lang>
{{out}}
<pre>middleThreeDigits(123): 123
Line 1,573 ⟶ 1,853:
 
=={{header|C_sharp|C#}}==
<langsyntaxhighlight lang="csharp">using System;
 
namespace RosettaCode
Line 1,585 ⟶ 1,865:
}
}
}</langsyntaxhighlight>
{{out}}
<pre>123:123
Line 1,608 ⟶ 1,888:
 
=={{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,726 ⟶ 2,062:
add 1 to digit-counter
end-perform.
exit paragraph.</langsyntaxhighlight>
Output
<pre> 123 --> 123
Line 1,746 ⟶ 2,082:
0 --> Number too small</pre>
Optimised version
<langsyntaxhighlight lang="cobol">identification division.
program-id. middle3.
environment division.
Line 1,818 ⟶ 2,154:
end-if.
 
</syntaxhighlight>
</lang>
Output
<pre> 123 --> 123
Line 1,840 ⟶ 2,176:
 
=={{header|Common Lisp}}==
===Solution #1===
<lang lisp>
<syntaxhighlight lang="lisp">
(defun mid3 (n)
(let ((a (abs n))
Line 1,853 ⟶ 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,881 ⟶ 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,903 ⟶ 2,317:
foreach (immutable n; failing)
writefln("middleThreeDigits(%s): %s", n, middleThreeDigits(n));
}</langsyntaxhighlight>
{{out}}
<pre>middleThreeDigits(123): 123
Line 1,929 ⟶ 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 2,015 ⟶ 2,429:
writefln("middleThreeDigits(cast(short)%d): %s", n, mtd);
}
}</langsyntaxhighlight>
{{out}}
<pre>middleThreeDigits(123): 123
Line 2,066 ⟶ 2,480:
 
=={{header|Dart}}==
<syntaxhighlight lang="text">
import'dart:math';
int length(int x)
Line 2,113 ⟶ 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 2,130 ⟶ 2,544:
$ endif
$ i = i + 1
$ goto loop</langsyntaxhighlight>
{{out}}
<pre>$ @middle_three_digits
Line 2,153 ⟶ 2,567:
=={{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 2,217 ⟶ 2,668:
 
end
</syntaxhighlight>
</lang>
{{out}}
<pre>
Line 2,241 ⟶ 2,692:
 
=={{header|Elena}}==
ELENA 56.0x :
<langsyntaxhighlight lang="elena">import system'routines;
import extensions;
Line 2,251 ⟶ 2,702:
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()
};
Line 2,266 ⟶ 2,717:
{
new int[]{123, 12345, 1234567, 987654321, 10001, -10001, -123, -100, 100, -12345, 1, 2, -1, -10, 2002, -2002, 0}
.forEach::(n)
{
console.printLine("middleThreeDigits(",n,"):",middleThreeDigits(n) |\\ on::(e => e.Message))
}
}</langsyntaxhighlight>
{{out}}
<pre>
Line 2,293 ⟶ 2,744:
 
=={{header|Elixir}}==
<langsyntaxhighlight Elixirlang="elixir">defmodule Middle do
def three(num) do
n = num |> abs |> to_string
Line 2,322 ⟶ 2,773:
e -> IO.puts e.message
end
end)</langsyntaxhighlight>
 
{{out}}
Line 2,346 ⟶ 2,797:
 
=={{header|Erlang}}==
<langsyntaxhighlight lang="erlang">%
-module(middle_three_digits).
-export([main/0]).
Line 2,385 ⟶ 2,836:
loop(X,N) when X>0 ->
loop(X-1, N div 10).
</syntaxhighlight>
</lang>
{{out}}
<pre>123
Line 2,408 ⟶ 2,859:
 
=={{header|ERRE}}==
<syntaxhighlight lang="erre">
<lang ERRE>
PROGRAM MIDDLE
 
Line 2,453 ⟶ 2,904:
END FOR
END PROGRAM
</syntaxhighlight>
</lang>
{{out}}
<pre>
Line 2,476 ⟶ 2,927:
 
=={{header|Factor}}==
<syntaxhighlight lang="text">USING: combinators formatting io kernel math math.parser
sequences ;
IN: rosetta-code.middle-three-digits
Line 2,504 ⟶ 2,955:
test-values [ dup "%9d : " printf middle-three ] each ;
 
MAIN: main</langsyntaxhighlight>
{{out}}
<pre>
Line 2,528 ⟶ 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,609 ⟶ 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,643 ⟶ 3,094:
Print
Print "Press any key to quit"
Sleep</langsyntaxhighlight>
 
{{out}}
Line 2,666 ⟶ 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,692 ⟶ 3,208:
Next
 
End</langsyntaxhighlight>
Output:
<pre>
Line 2,717 ⟶ 3,233:
 
File m3.go:
<langsyntaxhighlight lang="go">package m3
 
import (
Line 2,742 ⟶ 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,802 ⟶ 3,318:
t.Logf("d(%d) returns %q", tc.i, err)
}
}</langsyntaxhighlight>
{{out}}
Output of go test is normally terse:
Line 2,835 ⟶ 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,847 ⟶ 3,363:
var start = (s.length / 2) - 1
return s.substring(start, start + 3)
}</langsyntaxhighlight>
 
{{Output}}
Line 2,870 ⟶ 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,877 ⟶ 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,886 ⟶ 3,402:
println "$text cannot be converted: $error.message"
}
}</langsyntaxhighlight>
Output:
<pre> 123: 123
Line 2,907 ⟶ 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,917 ⟶ 3,435:
lng = length s
 
-- TEST ------------------------------- TEST -------------------------
main :: IO ()
main = do
Line 2,939 ⟶ 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,959 ⟶ 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,971 ⟶ 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,982 ⟶ 3,500:
else "wrong number of digits"
else "too short"
end</langsyntaxhighlight>
 
with output:
Line 3,007 ⟶ 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 3,031 ⟶ 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 3,060 ⟶ 3,600:
return s.substring(mid - 1, mid + 2);
}
}</langsyntaxhighlight>
<pre>middleThreeDigits(123): 123
middleThreeDigits(12345): 234
Line 3,084 ⟶ 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 3,093 ⟶ 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 3,116 ⟶ 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 3,241 ⟶ 3,781:
// MAIN ---
return main();
})();</langsyntaxhighlight>
{{Out}}
<pre>
Line 3,263 ⟶ 3,803:
 
=={{header|jq}}==
<langsyntaxhighlight lang="jq">def middle3:
if . < 0 then -. else . end
| tostring as $s
Line 3,272 ⟶ 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 3,290 ⟶ 3,830:
2002 => invalid length: 4
-2002 => invalid length: 4
0 => invalid length: 1 </langsyntaxhighlight>
 
=={{header|Julia}}==
{{works with|Julia|1.0.3}}
 
<langsyntaxhighlight lang="julia">using Printf
 
function middle3(n::Integer)
Line 3,308 ⟶ 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 3,330 ⟶ 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 3,364 ⟶ 3,904:
 
=={{header|Klingphix}}==
<langsyntaxhighlight Klingphixlang="klingphix">include ..\Utilitys.tlhy
 
( 123 12345 1234567 987654321 10001 -10001 -123 -100 100 -12345 1 2 -1 -10 2002 -2002 0 )
Line 3,378 ⟶ 3,918:
 
" " input
</syntaxhighlight>
</lang>
{{out}}
<pre>123 : 123
Line 3,399 ⟶ 3,939:
 
=={{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 3,422 ⟶ 3,962:
println(middleThree(123))// 123
println(middleThree(123555)) //null
}</langsyntaxhighlight>
 
=={{header|Lambdatalk}}==
<langsyntaxhighlight lang="scheme">
{def S 123 12345 1234567 987654321 10001 -10001 -123 -100 100 -12345
1 2 -1 -10 2002 -2002 0}
Line 3,467 ⟶ 4,007:
-2002: has an even number of digits
0: has not enough digits
</syntaxhighlight>
</lang>
 
=={{header|Lasso}}==
<langsyntaxhighlight Lassolang="lasso">define middlethree(value::integer) => {
local(
pos_value = math_abs(#value),
Line 3,491 ⟶ 4,031:
'<br />'
^}
'</pre>'</langsyntaxhighlight>
'''Output'''
<pre> 123: 123
Line 3,512 ⟶ 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 3,530 ⟶ 4,070:
]
 
bye</langsyntaxhighlight>
 
{{Output}}
Line 3,552 ⟶ 4,092:
 
=={{header|Lua}}==
<langsyntaxhighlight lang="lua">function middle_three(n)
if n < 0 then
n = -n
Line 3,577 ⟶ 4,117:
print(n, middle_three(n))
end
end</langsyntaxhighlight>
 
{{out}}
Line 3,599 ⟶ 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,617 ⟶ 4,157:
middleDigits(i);
printf("\n");
end do;</langsyntaxhighlight>
{{out}}
<pre>
Line 3,639 ⟶ 4,179:
</pre>
 
=={{header|Mathematica}}/{{header|Wolfram Language}}==
<langsyntaxhighlight Mathematicalang="mathematica">middleThree[n_Integer] :=
Block[{digits = IntegerDigits[n], len},
len = Length[digits];
Line 3,650 ⟶ 4,190:
100, -12345, 1, 2, -1, -10, 2002, -2002, 0};
 
Column[middleThree /@ testData]</langsyntaxhighlight>
{{out}}<pre>123
123
234
345
Line 3,668 ⟶ 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,686 ⟶ 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,712 ⟶ 4,250:
 
=={{header|MiniScript}}==
<langsyntaxhighlight MiniScriptlang="miniscript">middle3 = function(num)
if num < 0 then num = -num
s = str(num)
Line 3,724 ⟶ 4,262:
100, -12345, 1, 2, -1, -10, 2002, -2002, 0]
print test + " --> " + middle3(test)
end for</langsyntaxhighlight>
{{out}}
<pre>123 --> 123
Line 3,745 ⟶ 4,283:
 
=={{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,754 ⟶ 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,779 ⟶ 4,317:
;
map (println o middleThreeDigits) test_array;</langsyntaxhighlight>
Output:
<pre>123 --> 123
Line 3,801 ⟶ 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,811 ⟶ 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,835 ⟶ 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,881 ⟶ 4,419:
end
return text
</syntaxhighlight>
</lang>
'''Output:'''
<pre>
Line 3,911 ⟶ 4,449:
 
=={{header|NewLISP}}==
<syntaxhighlight lang="newlisp">
<lang NewLISP>
(define (middle3 x)
(if (even? (length x))
Line 3,923 ⟶ 4,461:
 
(map middle3 lst)
</syntaxhighlight>
</lang>
'''Output:'''
<pre>
Line 3,946 ⟶ 4,484:
 
=={{header|Nim}}==
<langsyntaxhighlight lang="nim">proc middleThreeDigits(i: int): string =
var s = $abs(i)
if s.len < 3 or s.len mod 2 == 0:
Line 3,959 ⟶ 4,497:
var answer = try: middleThreeDigits(i)
except ValueError: getCurrentExceptionMsg()
echo "middleThreeDigits(", i, ") returned: ", answer</langsyntaxhighlight>
 
{{out}}
Line 3,981 ⟶ 4,519:
 
=={{header|Objeck}}==
<langsyntaxhighlight lang="objeck">
class Test {
function : Main(args : String[]) ~ Nil {
Line 3,994 ⟶ 4,532:
}
 
}</langsyntaxhighlight>
 
<pre>
Line 4,018 ⟶ 4,556:
=={{header|OCaml}}==
 
<langsyntaxhighlight lang="ocaml">let even x = (x land 1) <> 1
 
let middle_three_digits x =
Line 4,042 ⟶ 4,580:
print_endline "Should fail:";
List.iter print failing;
;;</langsyntaxhighlight>
 
{{out}}
Line 4,070 ⟶ 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 4,094 ⟶ 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 4,145 ⟶ 4,683:
writeln(n:9,': ',GetMid3dig(Test[i]));
end;
end.</langsyntaxhighlight>
{{out}}
<pre> 123: 123
Line 4,167 ⟶ 4,705:
 
=={{header|Perl}}==
<langsyntaxhighlight Perllang="perl">#!/usr/bin/perl
use strict ;
use warnings ;
Line 4,192 ⟶ 4,730:
1, 2, -1, -10, 2002, -2002, 0 ) ;
map { middlethree( $_ ) } @numbers ;
</syntaxhighlight>
</lang>
{{out}}
<pre>Middle 3 digits of 123 : 123 !
Line 4,214 ⟶ 4,752:
 
=={{header|Phix}}==
<!--<langsyntaxhighlight Phixlang="phix">(phixonline)-->
<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>
<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>
Line 4,226 ⟶ 4,764:
<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>
<span style="color: #008080;">end</span> <span style="color: #008080;">for</span>
<!--</langsyntaxhighlight>-->
{{out}}
<pre>
Line 4,249 ⟶ 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 4,287 ⟶ 4,825:
{
echo $nums.' : '.middlethree($nums). '<br>';
}</langsyntaxhighlight>
Output:
<pre>123 : 123
Line 4,306 ⟶ 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 4,317 ⟶ 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 4,340 ⟶ 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 4,367 ⟶ 5,011:
 
end middle;
</syntaxhighlight>
</lang>
Output:
<pre>
Line 4,389 ⟶ 5,033:
 
=={{header|Plain English}}==
<langsyntaxhighlight lang="plainenglish">To run:
Start up.
Test 123.
Line 4,425 ⟶ 5,069:
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.</langsyntaxhighlight>
{{out}}
<pre>
Line 4,448 ⟶ 5,092:
 
=={{header|PowerShell}}==
<langsyntaxhighlight lang="powershell">function middle3($inp){
 
$str = [Math]::abs($inp)
Line 4,471 ⟶ 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 4,494 ⟶ 5,138:
{{works with|SWI-Prolog|6}}
 
<langsyntaxhighlight lang="prolog">
middle_3_digits(Number, [D1,D2,D3]) :-
verify_middle_3_able(Number, Digits),
Line 4,509 ⟶ 5,153:
; true
).
</syntaxhighlight>
</lang>
 
 
Test code:
 
<langsyntaxhighlight lang="prolog">
test_correct :-
TestCases = [123, 12345, 1234567, 987654321, 10001, -10001, -123, -100, 100, -12345],
Line 4,521 ⟶ 5,165:
format('Middle 3 digits of ~w ~30|: ~w~n', [TestCase, Result])
).
</syntaxhighlight>
</lang>
 
 
Line 4,561 ⟶ 5,205:
=={{header|Python}}==
===Procedural===
<langsyntaxhighlight lang="python">>>> def middle_three_digits(i):
s = str(abs(i))
length = len(s)
Line 4,595 ⟶ 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===
Using a composable option type as an alternative to error handling:
{{Trans|Haskell}}
<langsyntaxhighlight lang="python">'''Middle 3 digits'''
 
 
Line 4,684 ⟶ 5,328:
 
if __name__ == '__main__':
main()</langsyntaxhighlight>
{{Out}}
<pre>Middle three digits, where defined:
Line 4,709 ⟶ 5,353:
=={{header|Quackery}}==
 
<langsyntaxhighlight Quackerylang="quackery"> [ 1 & not ] is even ( n --> b )
 
[ over size -
Line 4,736 ⟶ 5,380:
[ dup number$ 9 justify echo$
say " --> "
middle3 echo$ cr ]</langsyntaxhighlight>
 
{{out}}
Line 4,759 ⟶ 5,403:
 
=={{header|Racket}}==
<langsyntaxhighlight lang="scheme">#lang racket
(define (middle x)
(cond
Line 4,772 ⟶ 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" perl6line>sub middle-three($n) {
given $n.abs {
when .chars < 3 { "$n is too short" }
Line 4,791 ⟶ 5,435:
123 12345 1234567 987654321 10001 -10001 -123 -100 100 -12345
1 2 -1 -10 2002 -2002 0
>;</langsyntaxhighlight>
{{out}}
<pre>The three middle digits of 123 are: 123
Line 4,812 ⟶ 5,456:
 
It is also possible to write a regular expression with a code assertion:
<syntaxhighlight lang="raku" perl6line>for [\~] ^10 { say "$_ => $()" if m/^^(\d+) <(\d**3)> (\d+) $$ <?{ $0.chars == $1.chars}> / }</langsyntaxhighlight>
{{out}}
<pre>01234 => 123
Line 4,820 ⟶ 5,464:
=={{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,847 ⟶ 5,491:
End
End
Return res</langsyntaxhighlight>
Output:
<pre>
Line 4,876 ⟶ 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,891 ⟶ 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,921 ⟶ 5,565:
 
=={{header|Ring}}==
<langsyntaxhighlight lang="ring">
n = 1234567
middle(n)
Line 4,932 ⟶ 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,949 ⟶ 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,966 ⟶ 5,632:
puts e
end
end</langsyntaxhighlight>
{{out}}
<pre>
Line 4,989 ⟶ 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 5,018 ⟶ 5,684:
print_result(*i);
}
}</langsyntaxhighlight>
 
{{Out}}
Line 5,054 ⟶ 5,720:
course just list the numbers backwards.
</pre>
<langsyntaxhighlight Slang="s-lang">
define m3(i)
{
Line 5,084 ⟶ 5,750:
#endif
1, 2, -1, -10, 2002, -2002, 0 } );
</syntaxhighlight>
</lang>
{{out}}<pre>
" 123: 123"
Line 5,108 ⟶ 5,774:
 
=={{header|Scala}}==
<langsyntaxhighlight lang="scala">/**
* Optionally return the middle three digits of an integer.
*
Line 5,129 ⟶ 5,795:
case Some(v) => "%03d".format(v) // Format the value, force leading zeroes
} mkString("\n")
</syntaxhighlight>
</lang>
{{out}}
<pre>123
Line 5,148 ⟶ 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 5,174 ⟶ 5,874:
writeln(number <& ": " <& middle3(number));
end for;
end func;</langsyntaxhighlight>
 
{{out}}
Line 5,198 ⟶ 5,898:
 
=={{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.
<lang sensetalk>
<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 itemnum ofin inputs
put itnum into output
put middle3digits of itnum into character 15 of output -- will autofill with "."s
put output
end repeat
Line 5,219 ⟶ 5,919:
return digits joined by empty
end middle3digits
</syntaxhighlight>
</lang>
{{out}}
Output:
<pre>
123...........123
Line 5,243 ⟶ 5,943:
=={{header|Sidef}}==
{{trans|Raku}}
<langsyntaxhighlight lang="ruby">func middle_three(n) {
var l = n.len;
if (l < 3) {
"#{n} is too short"
Line 5,250 ⟶ 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 5,257 ⟶ 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 5,281 ⟶ 5,981:
 
=={{header|SQL}}==
<langsyntaxhighlight lang="sql">;WITH DATA
AS (SELECT CAST(ABS(NUMBER) AS NVARCHAR(MAX)) charNum,
NUMBER,
Line 5,292 ⟶ 5,992:
END Output,
NUMBER Input
FROM DATA </langsyntaxhighlight>
 
<pre>
Line 5,323 ⟶ 6,023:
 
=={{header|Swift}}==
<langsyntaxhighlight lang="swift">var num:Int = \\enter your number here
if num<0{num = -num}
var numArray:[Int]=[]
Line 5,338 ⟶ 6,038:
i=i/2
print("\(numArray[i+1]),\(numArray[i]),\(numArray[i-1])")
}</langsyntaxhighlight>
<pre>
123: 123
Line 5,360 ⟶ 6,060:
 
=={{header|Tcl}}==
<langsyntaxhighlight lang="tcl">proc middleThree n {
if {$n < 0} {
set n [expr {-$n}]
Line 5,373 ⟶ 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 5,386 ⟶ 6,086:
puts "found for ${n}: $mid"
}
}</langsyntaxhighlight>
{{out}}
<pre>
Line 5,407 ⟶ 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 5,413 ⟶ 6,220:
{{works with|Z Shell}}
 
<langsyntaxhighlight lang="bash">function middle3digits
{
typeset -i n="${1#-}"
Line 5,435 ⟶ 6,242:
printf "%10d: " $n
middle3digits "$n"
done</langsyntaxhighlight>
 
Output: <pre> 123: 123
Line 5,457 ⟶ 6,264:
=={{header|VBA}}==
 
<syntaxhighlight lang="vb">
<lang vb>
Option Explicit
 
Line 5,479 ⟶ 6,286:
End If
End Function
</syntaxhighlight>
</lang>
{{out}}
<pre>123 Return : 123
Line 5,500 ⟶ 6,307:
 
=={{header|VBScript}}==
<langsyntaxhighlight lang="vb">'http://rosettacode.org/wiki/Middle_three_digits
 
Function mid3n(n)
Line 5,520 ⟶ 6,327:
WScript.StdOut.Write n & ": " & mid3n(n)
WScript.StdOut.WriteLine
Next</langsyntaxhighlight>
{{Out}}
<pre>
Line 5,543 ⟶ 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 5,571 ⟶ 6,378:
}
Buf_Quit(OK)
Return </langsyntaxhighlight>
 
Output:
Line 5,591 ⟶ 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 5,600 ⟶ 6,452:
mid (int max/2))
if (and odd?.max (max >= 3))
(digits mid-1 mid+2)</langsyntaxhighlight>
 
'''Output'''
Line 5,642 ⟶ 6,494:
=={{header|Wren}}==
{{libheader|Wren-fmt}}
<langsyntaxhighlight ecmascriptlang="wren">import "./fmt" for Fmt
 
var middle3 = Fn.new { |n|
Line 5,659 ⟶ 6,511:
 
for (e in a) {
SystemFmt.print("%(Fmt.s(9$9d -> $n", e)), -> %(middle3.call(e))")
}</langsyntaxhighlight>
 
{{out}}
Line 5,684 ⟶ 6,536:
 
=={{header|XPL0}}==
<langsyntaxhighlight XPL0lang="xpl0">include c:\cxpl\stdlib;
 
func Mid3Digits(I); \Return the middle three digits of I
Line 5,707 ⟶ 6,559:
Text(0, Mid3Digits(Passing(X))); CrLf(0);
];
]</langsyntaxhighlight>
 
{{out}}
Line 5,731 ⟶ 6,583:
 
=={{header|zkl}}==
<langsyntaxhighlight lang="zkl">fcn middle(ns){
ns.apply("toString").apply('-("-"))
.apply(fcn(n){nl:=n.len();
Line 5,739 ⟶ 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