g | x | w | all
Bytes Lang Time Link
040Gema231224T212337Zmanatwor
875Vyxal231224T192640ZPacmanbo
009Thunno 2 j230723T095328ZThe Thon
033Excel VBA180111T192450ZTaylor A
9589SNOBOL4 CSNOBOL4180104T165922ZGiuseppe
018Jelly180111T190405Zdylnan
163Sinclair ZX81/Timex TS1000/1500 BASIC180104T144248ZShaun Be
020Jelly171219T155935ZDELETE_M
083Clean171207T205449ZΟurous
030Stacked171201T133510ZConor O&
218Java171208T183748ZDevelopi
062Mathematica171201T174411ZMatjazGo
013Pip171204T050429ZDLosc
048R171202T003752Zduckmayr
018Husk171202T175747Zბიმო
012Husk171202T195242ZZgarb
025bash171201T123142ZNahuel F
035C# 6.0171202T155623Zuser7651
040PowerShell171202T004053Zbriantis
037Python 3.6171201T112339ZLescurel
045PHP171201T115849ZTitus
029Python 2171201T110013Ztotallyh
3765Swift171201T214404ZEric
008Japt171201T171841ZShaggy
012Japt171201T150112ZOliver
049PHP171201T193631ZMatias V
028Ruby171201T151055ZJér
nan171201T175512ZBrad Gil
046Tcl171201T175255Zsergiol
nanPerl 5171201T122832ZNahuel F
2526Perl171201T144221ZZaid
054Haskell171201T113608Ztotallyh
012Pyth171201T100630ZMr. Xcod
042JavaScript ES6171201T120148Zedc65
045C gcc171201T140137ZConor O&
044Octave171201T133104ZStewie G
039Retina171201T095333ZMartin E
013Charcoal171201T114458ZCharlie
033C171201T120857ZSteadybo
029Excel171201T114953ZWernisch
047Java OpenJDK 8171201T114840ZOlivier
029Python171201T095404ZColera S
023Alice171201T104657ZMartin E
01005AB1E171201T102526ZEmigna
118Mathematica171201T103307ZZaMoC
056C#171201T100409ZLiefdeWe

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

Try it online! / Try all test cases online!

Vyxal, 70 bitsv2, 8.75 bytes

ȧS∆Z¹±SṪp

Try it Online!

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Ṙṛ$ʂṄ'-×

Try it online!

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)

Try it online!

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¤¤;

Try it online!

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.

Jelly, 20 bytes

0;$L<⁹$$¿
ṣ”-Ç€0¦j”-

Try it online!

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]}

Try it online!

Stacked, 30 bytes

[@x'@:'!'\d+'['0'x pad]1/repl]

Try it online!

Highlighted:

just the above thing

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]]&

Try it online!

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)

Try it online!

-8 bytes thanks to djhurio

Explanation

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⁰

Try it online!

Husk, 12 bytes

Ö±Ωo≥⁰#±:'0s

Try it online!

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.

bash, 27, 25 bytes

-2 bytes thanks to Bruce Forte

printf %0$[$2+($1<0)]d $1

try it online

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))

Try it online!

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.

Python 2, 29 bytes

lambda x,y:x.zfill(y+(x<'.'))

Try it online!

Just str.zfill comes so close.

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}'-

Try it

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.

Japt, 14 12 bytes

Saved 2 bytes thanks to @ETHproductions

s r"%d+"_ù0V

Try it online

PHP, 49 bytes

echo str_pad($argv[1],$argv[2],'0',STR_PAD_LEFT);

Ruby, 31 28 bytes

Thanks Carl for saving 3 bytes using interpolation.

->x,y{"%0#{y+(x<0?1:0)}d"%x}

Try it online!

Perl 6,  39 31  30 bytes

->\a,\b{'-'x(0>a)~a.abs.fmt("\%0{b}d")}

Test it

->\a,\b{a.fmt("\%0{b+(0>a)}d")}

Test it

{$^a.fmt: '%0'~$^b+(0>$a)~'d'}

Test it

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'
}

Tcl, 46 bytes

proc Z n\ p {format %0[expr $n<0?$p+1:$p]d $n}

Try it online!

Perl 5, 22 + 1 (-n) = 23 bytes

printf"%0*d",<>+/-/,$_

Try it online

Perl, 25 + -n flag = 26 bytes

printf"%0*d",<>+($_<0),$_

Try it online!

Haskell, 54 bytes

x#y|s<-show$abs$x=['-'|x<0]++('0'<$[length s+1..y])++s

Try it online!

Pyth, 12 bytes

%"%0*d",+E>0

Try it here!

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));}

Try it online!

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.

Octave, 44 bytes

@(x,y)fprintf(['%0',num2str(y+(x<0)),'d'],x)

Try it online!

Retina, 39 bytes

\d+$
$*0
((\d)*),(?<-2>-0+|0)*(0*)
$3$1

Try it online!

Input should be comma-separated with the number first and the width second.

Charcoal, 16 13 bytes

‹N⁰﹪⁺⁺%0ηd↔Iθ

Try it online!

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

C, 33 bytes

f(x,y){printf("%0*d",y+(x<0),x);}

Try it online!

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)

Try it online!

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)

Try it online!

Alice, 23 bytes

/oRe./'+Ao
\I*tI&0-R$@/

Try it online!

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-×ì'-†

Try it online!

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]])&


Try it online!

C#, 56 bytes

Try it Online!

a=>b=>(a<0?"-":"")+((a<0?-a:a)+"").PadLeft(b<0?0:b,'0')