| Bytes | Lang | Time | Link |
|---|---|---|---|
| 040 | Gema | 231224T212337Z | manatwor |
| 875 | Vyxal | 231224T192640Z | Pacmanbo |
| 009 | Thunno 2 j | 230723T095328Z | The Thon |
| 033 | Excel VBA | 180111T192450Z | Taylor A |
| 9589 | SNOBOL4 CSNOBOL4 | 180104T165922Z | Giuseppe |
| 018 | Jelly | 180111T190405Z | dylnan |
| 163 | Sinclair ZX81/Timex TS1000/1500 BASIC | 180104T144248Z | Shaun Be |
| 020 | Jelly | 171219T155935Z | DELETE_M |
| 083 | Clean | 171207T205449Z | Οurous |
| 030 | Stacked | 171201T133510Z | Conor O& |
| 218 | Java | 171208T183748Z | Developi |
| 062 | Mathematica | 171201T174411Z | MatjazGo |
| 013 | Pip | 171204T050429Z | DLosc |
| 048 | R | 171202T003752Z | duckmayr |
| 018 | Husk | 171202T175747Z | ბიმო |
| 012 | Husk | 171202T195242Z | Zgarb |
| 025 | bash | 171201T123142Z | Nahuel F |
| 035 | C# 6.0 | 171202T155623Z | user7651 |
| 040 | PowerShell | 171202T004053Z | briantis |
| 037 | Python 3.6 | 171201T112339Z | Lescurel |
| 045 | PHP | 171201T115849Z | Titus |
| 029 | Python 2 | 171201T110013Z | totallyh |
| 3765 | Swift | 171201T214404Z | Eric |
| 008 | Japt | 171201T171841Z | Shaggy |
| 012 | Japt | 171201T150112Z | Oliver |
| 049 | PHP | 171201T193631Z | Matias V |
| 028 | Ruby | 171201T151055Z | Jér |
| nan | 171201T175512Z | Brad Gil | |
| 046 | Tcl | 171201T175255Z | sergiol |
| nan | Perl 5 | 171201T122832Z | Nahuel F |
| 2526 | Perl | 171201T144221Z | Zaid |
| 054 | Haskell | 171201T113608Z | totallyh |
| 012 | Pyth | 171201T100630Z | Mr. Xcod |
| 042 | JavaScript ES6 | 171201T120148Z | edc65 |
| 045 | C gcc | 171201T140137Z | Conor O& |
| 044 | Octave | 171201T133104Z | Stewie G |
| 039 | Retina | 171201T095333Z | Martin E |
| 013 | Charcoal | 171201T114458Z | Charlie |
| 033 | C | 171201T120857Z | Steadybo |
| 029 | Excel | 171201T114953Z | Wernisch |
| 047 | Java OpenJDK 8 | 171201T114840Z | Olivier |
| 029 | Python | 171201T095404Z | Colera S |
| 023 | Alice | 171201T104657Z | Martin E |
| 010 | 05AB1E | 171201T102526Z | Emigna |
| 118 | Mathematica | 171201T103307Z | ZaMoC |
| 056 | C# | 171201T100409Z | LiefdeWe |
Gema, 40 characters
<y><D>,<N>=$1@subst{\\ =0;@right{$3;$2}}
(Not really for Gema. For some weird reason it can only pad with spaces.)
Sample run:
bash-5.2$ gema '<y><D>,<N>=$1@subst{\\ =0;@right{$3;$2}}' <<< '-7,3'
-007
Vyxal, 70 bitsv2, 8.75 bytes
ȧS∆Z¹±SṪp
Bitstring:
1001110000000100000100010000100111100010101011011000110001011000011111
Idk why Vyxal 2 doesnt have an "is negative?" element but i found a way around that
Thunno 2 j, 9 bytes
AṘṛ$ʂṄ'-×
Explanation
AṘṛ$ʂṄ'-× '# Implicit input
AṘ # Take the absolute value and convert to string
ṛ # Pad with zeros to length of second input
$ʂṄ # Check if the first input was negative
'-× '# If it was, push a "-"
# Implicit output of joined stack
Excel VBA, 33 Bytes
Anonymous VBE immediate window function that takes input as n from [A1] and length from [B1] and outputs the appropriately formatted string to the VBE immediate window
?Format([A1],[Rept(0,Max(1,B1))])
SNOBOL4 (CSNOBOL4), 95 89 bytes
DEFINE('F(X,B)')
F L =GT(B) B
N =LT(X) 1
F =DUPL('-',N) LPAD(-1 ^ N * X,L,0) :(RETURN)
defining a function is equivalent to a full program in bytes, so I figured I'd do this instead.
Jelly, 18 bytes
R¬+Ṛ}AṚṾ€”-x⁴<0¤¤;
Takes y and x (in that order) as integers.
Explanation
Example input 5 and -123.
R¬+Ṛ}AṚṾ€”-x⁴<0¤¤; Dyadic link
R¬ Not the range of y. This gives a list of y zeroes. [0,0,0,0,0]
Ṛ} Reverse the digits of x. [-3,-2,-1]
+ Add these lists. [-3,-2,-1,0,0]
A Absolute value. [3,2,1,0,0].
Ṛ Reverse. [0,0,1,2,3]
Ṿ€ Make each digit a string. '00123'
”- The character '-'.
⁴<0 x<0? 0 or 1. (1 in this example)
x Repeat '-' 0 or 1 times
¤¤ Closes ”-x⁴<0 as a nilad
; Prepend '-' to '00123'
The absolute difference atom ạ would work here over + making A unnecessary except for the case where y is zero or negative where it doesn't work.
Sinclair ZX81/Timex TS1000/1500 BASIC, ~163 tokenized BASIC bytes
1 DIM A(SGN PI,VAL "2")
2 LET A(SGN PI,SGN PI)=NOT PI
3 LET A(SGN PI,VAL "2")=INT PI
4 IF A(SGN PI,SGN PI)<NOT PI THEN PRINT "-";
5 IF A(SGN PI,VAL "2")=SGN PI THEN GOTO INT PI*PI
6 FOR I=VAL "2" TO A(SGN PI,VAL "2")
7 PRINT NOT PI;
8 NEXT I
9 PRINT ABS A(SGN PI,SGN PI)
Explanations: ZX81 BASIC is quite costly when storing numbers as each number is stored as a 5 byte (I think) floating point number even if you store an integer value like 1. Even line numbers cost 5 bytes per line, then add in the NEW LINE character at the end of each line, and the lowest byte count for a BASIC line in Sinclair ZX81 BASIC is 7 (for instance, 1 PRINT). SGN PI is 1, and costs fewer bytes than 1 on this basis, NOT PI is 0 and costs two bytes etc.
- Line
1sets up a numeric array1, 2; arrays are not zero-indexed in this case. - Line
2setsA[1, 1]to zero. - Line
3setsA[1, 2]to 3, so the test case is(1,3). - Line
4tests to see if the number to be printed is negative; if so, a minus sign is displayed. - Line
5checks if the padding is set to 1, if so we don't need to print any leading zeros. - Line
6then loops through from 2 to the value of our padding (in this case, 3). - Line
7prints the leading zeros. - Line
8ends the loop. - Line
9prints the positive value of ourA[1,1], which in this case is zero.
Jelly, 20 bytes
0;$L<⁹$$¿
ṣ”-Ç€0¦j”-
Take first input x as a string.
Apparently there is no existing Jelly answer...
L<¥ doesn't seem to work.
Clean, 90 86 83 bytes
import StdEnv
@x y=if(y<0)"-"""+++{if(c>'-')c'0'\\c<-rjustify x[k\\k<-:toString y]}
Stacked, 30 bytes
[@x'@:'!'\d+'['0'x pad]1/repl]
Highlighted:
Explanation
[@x'@:'!'\d+'['0'x pad]1/repl]
[ ] anonymous function, take two args: (y x)
@x name pad length argument
'@:'! convert to string*
'\d+'[ ]1/repl replace all runs of digits with...
'0'x pad ...the digits padded to x '0's
Stringification
Usually, one would use tostr to convert something to a string; however, due to the way string formatting works...
'@:'!
! format the string
'@:' apply the `:` function t the top of the stack
this creates a sub-stack, and : duplicates.
the formatting obtains the top value, which is just the original TOS,
and casts it to a string
The reason we use '@:'! instead of tostr is to avoid the space between @x and tostr.
Java, 218 bytes
import org.apache.commons.lang3.StringUtils;interface B{static void main(String z[]){int x=Integer.parseInt(z[1]);if(x>z[0].length()){System.out.printf(StringUtils.leftPad(z[0],x,"0"));}else{System.out.printf(z[0]);}}}
Ungolfed:
import org.apache.commons.lang3.StringUtils;
interface B {
static void main(String z[]) {
int x = Integer.parseInt(z[1]);
if (x > z[0].length()) {
System.out.printf(StringUtils.leftPad(z[0], x, "0"));
} else {
System.out.printf(z[0]);
}
}
}
Mathematica, 63 62 bytes
If[#<0,"-",""]<>IntegerString[#,10,Max[#2,IntegerLength@#,1]]&
Pip, 13 bytes
aR+XD0Xb-#_._
Takes the number and minimum number of digits as command-line arguments. Try it online!
Explanation
a, b are cmdline args; XD is regex `\d` (implicit)
aR In the number a, replace
+XD a run of digits (regex `\d+`)
with this callback function:
0X 0 string-multiplied by
b-#_ minimum digit count minus length of match
._ to which concatenate the match itself
Autoprint the result of the replacement
Since string-multiplication gives an empty string when the right operand is negative, this works correctly for all test cases.
R, 56 48 bytes
function(x,y)sprintf(paste0("%0",y+(x<0),"d"),x)
-8 bytes thanks to djhurio
Explanation
sprintf("%0zd",x)returnsxas a string padded with zeros to be of lengthzpaste0("%0",y+(x<0),"d")constructs the string"%0zd", wherezisy, plus 1 ifxis less than zero- If
zis less than the number of digits inx,xis printed as a string as is
Husk, 18 bytes
Likely not the right approach, this is feels really long for Husk, but there wasn't one already.
F+Ṁ+R'0-Ld⁰¹↕='-s⁰
Husk, 12 bytes
Ö±Ωo≥⁰#±:'0s
Explanation
Ö±Ωo≥⁰#±:'0s Inputs are y=4 and x=-20
s Convert x to string: "-20"
:'0 Prepend '0'
Ω until
#± the number of digits
o≥⁰ is at least y: "00-20"
Ö± Sort by is-digit: "-0020"
Print implicitly.
C# 6.0, 35 bytes
(x,y)=>(x.ToString($"D{y<0?0:y}"));
Alternative solution (51 bytes)
(x,y)=>(x.ToString(string.Format("D{0}",y<0?0:y)));
PowerShell, 25 40 bytes
param($a,$b)$a|% *g $("D$b"*($b|% *o 0))
Explanation
This calls .ToString() on the number with a generated format string, but multiplies it by -1, 0, or 1 based on whether $b (y) is negative, 0, or positive respectively; this is to handle negative y values which format strings don't by themselves.
This seems to require wrapping negative numbers in a substatement () for it to work which is just a quirk of the invocation when using literals; if passed variables of type integer, it would not need that.
Python 3.6, 28 37 bytes
lambda x,y:f'{x:0{(y,0)[y<0]+(x<0)}}'
Try it online! (Test case from Colera Su's answer)
Taking advantage of the new way to format strings in python 3.6
+9 bytes to handle y<0
PHP, 45 bytes
printf("%0".($argv[2]+(0>$n=$argv[1])).d,$n);
or
[,$n,$e]=$argv;printf("%0".($e+(0>$n)).d,$n); # requires PHP 7.1 or later
Run with -nr or try them online.
Swift, 37 bytes (65 inside a function):
String(format:"%0\(y+(x<0 ?1:0))d",x)
Inside a function:
func c(x:Int,y:Int){print(String(format:"%0\(y+(x<0 ?1:0))d",x))}
Japt, 13 8 bytes
Takes first input (x) as a string.
®©ùTV}'-
Saved a massive 5 bytes thanks to ETHproductions.
Explanation
Implicit input of string U=x and integer V=y.
® }'- splits U to an array on the minus symbol, maps over it and rejoins it to a string with a minus symbol.
© is logical AND (&&) so if the current element is truthy (a non-empty string) then pad left (ù) with 0 (T) to length V.
PHP, 49 bytes
echo str_pad($argv[1],$argv[2],'0',STR_PAD_LEFT);
Perl 6, 39 31 30 bytes
->\a,\b{'-'x(0>a)~a.abs.fmt("\%0{b}d")}
->\a,\b{a.fmt("\%0{b+(0>a)}d")}
{$^a.fmt: '%0'~$^b+(0>$a)~'d'}
Expanded:
{ # bare block lambda with placeholder parameters 「$a」 and 「$b」
$^a # declare and use first parameter
.fmt: # format it
'%0' # '%05d'
~
$^b # make it 「$b」 digits wide
+ (0>$a) # add 1 if 「$a」 is negative
~
'd'
}
JavaScript (ES6), 42
Recursive, parameters in reverse order, first y then x. And Currying
y=>r=x=>x<0?'-'+r(-x):`${x}`.padStart(y,0)
Test
var F=
y=>r=x=>x<0?'-'+r(-x):`${x}`.padStart(y,0)
;`IN: (1,1) OUT: "1"
IN: (1,2) OUT: "01"
IN: (10,1) OUT: "10"
IN: (-7,3) OUT: "-007"
IN: (-1,1) OUT: "-1"
IN: (10,-1) OUT: "10"
IN: (0,0) OUT: "0"
IN: (0,1) OUT: "0"
IN: (0,4) OUT: "0000"`
.split(`\n`).map(r => r.match(/[-\d]+/g))
.forEach(([x,y,k])=>{
o = F(y)(x)
ok = o == k
console.log(ok?'OK':'KO',x,y,'->', o)
})
C (gcc), 45 bytes
f(x,y){printf("%s%0*i","-"+(x>=0),y,abs(x));}
Explanation
printf formats three arguments:
%s -> "-"+(x>=0)
%0*i -> y
-> abs(x)
%s formats the string "-"+(x>=0). "-" is really just an address, something like 41961441. In memory, this looks something like this:
MEMORY ADDRESS | 41961441 41961442 ...
VALUE | 45 ('-') 0 (0x00) ...
When formatted into a string, C takes the address (say 41961441) and keeps on acquiring characters until a null byte (0x00) is met. When x is less than zero, the value "-"+(x>=0) has that of the original address (41961441). Otherwise, x>=0 is 1, so the expression becomes "-"+1, which points the null byte after "-", which prints nothing.
%0*i prints an integer padded with a specified number of 0s. y denotes this number. We pad abs(x) to avoid the negative in some arguments.
Retina, 39 bytes
\d+$
$*0
((\d)*),(?<-2>-0+|0)*(0*)
$3$1
Input should be comma-separated with the number first and the width second.
Charcoal, 16 13 bytes
‹N⁰﹪⁺⁺%0ηd↔Iθ
This is the shortest I could get using Charcoal without printing leading or trailing whitespaces. At least I am now starting to understand how to use the Modulo function to format strings.
The deverbosed code is as follows:
Print(Less(InputNumber(),0)); # Prints a - if the first input is less than 0
Print(Modulo(Add(Add("%0",h),"d"),Abs(Cast(q)))); # q: first input; h: second input
- 3 bytes saved thanks to Neil!
Excel, 29 bytes
Using Excel's TEXT functionality ("Converts a value to text in a specific number format").
x in A1, y in B1
=TEXT(A1,REPT("0",MAX(1,B1)))
Java (OpenJDK 8), 47 bytes
x->y->"".format("%0"+((y<1?1:y)-(x>>31))+"d",x)
At first I thought, easy, 30 chars max (which is quite short when manipulating strings in Java). Then the exceptions happened.
Python, 29 bytes
Take input as f(x,y). Using Python's % operator.
lambda x,y:'%0*d'%(y+(x<0),x)
Alice, 23 bytes
/oRe./'+Ao
\I*tI&0-R$@/
Input should be linefeed-separated with the number on the first line and the width on the second.
Explanation
/...
\...@/
This is the usual framework for linear programs in Ordinal mode. The only catch in this case is this bit:
.../...
...&...
This causes the IP to enter Cardinal mode vertically and execute just the & in Cardinal mode before resuming in Ordinal mode.
Unfolding the zigzag control flow then gives:
IRt.&'-A$o*eI/&/0+Ro@
I Read the first line of input (the value) as a string.
R Reverse the string.
t. Split off the last character and duplicate it.
& Fold the next command over this string. This doesn't really do anything,
because the string contains only one character (so folding the next
command is identical to executing it normally).
'- Push "-".
A Set intersection. Gives "-" for negative inputs and "" otherwise.
$o If it's "-", print it, otherwise it must have been a digit which we
leave on the stack.
* Join the digit back onto the number. If the number was negative, this
joins the (absolute value of the) number to an implicit empty string,
doing nothing.
e Push an empty string.
I Read the width W.
/&/ Iterate the next command W times.
0 Append a zero. So we get a string of W zeros on top of the absolute
value of the input number.
+ Superimpose. This takes the character-wise maximum of both strings
and appends extraneous characters from the longer string. Since the
string of zeros can never be larger than the digits in the input,
the input itself will be uneffected, but extraneous zeros are appended,
padding the string to the required length.
R Reverse the result.
o Print it.
@ Terminate the program.
Here are two alternatives, also at 23 bytes, which use Cardinal H (abs) to get rid of the -:
/R.I&0-RoH
\Ie#\'+Ao\@/
/R.H#/.+Xo
\Ie\I&0QRo@/
In principle, these are a command shorter, but the & doesn't fit into a position where there's a 1-character string on the stack, so we need to skip it with a #.
05AB1E, 11 10 bytes
Input given as amount_of_digits, number
ÎIÄg-×ì'-†
Explanation
Î # push 0 and first input
IÄ # push the absolute value of the second input
g # length
- # subtract, (input1-len(abs(input2))
× # repeat the zero that many times
ì # prepend to the second input
'-† # move any "-" to the front
Mathematica, 118 bytes
(j=ToString;If[#2<=0,j@#,If[(z=IntegerLength@#)>=#2,t=z,t=#2];s=j/@PadLeft[IntegerDigits@#,t];If[#>=0,""<>s,"-"<>s]])&
