[Question]
  [
# The challenge
Given two integers as input (`x` and `y`), output `x` as a string with as many leading zeroes necessary for it to be `y` characters long without the sign.
## Rules
* If `x` has more than `y` digits, output `x` as string without modification.
* Output as integer is not accepted, even if there are no leading zeroes.
* When `x` is negative, keep the `-` as is and operate on the absolute value.
* Negative `y` should be treated as 0, meaning you output `x` as is (but as string)
### Examples:
```
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"
```
Shortest code in bytes wins, standard loopholes apply.
  
[Answer]
# [Pyth](https://github.com/isaacg1/pyth), 12 bytes
```
%"%0*d",+E>0
```
**[Try it here!](https://pyth.herokuapp.com/?code=%25%22%250%2ad%22%2C%2BE%3E0&input=-7%0A3&debug=0)**
[Answer]
# [Python 2](https://docs.python.org/2/), 29 bytes
```
lambda x,y:x.zfill(y+(x<'.'))
```
[Try it online!](https://tio.run/##K6gsycjPM/qfZhvzPycxNyklUaFCp9KqQq8qLTMnR6NSW6PCRl1PXVPzf0lqcUmxgq1CNJcCEGioG6rrKBhq6iDxjBA8AxRJXXMg1xjOBUkaoKrVNdTkiuVKyy8C2q5QqZCZpwC2zgqspqAoM69EIU0DJKX5HwA "Python 2 – Try It Online")
Just `str.zfill` comes so close.
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E), ~~11~~ 10 bytes
Input given as `amount_of_digits, number`
```
ÎIÄg-×ì'-†
```
[Try it online!](https://tio.run/##MzBNTDJM/f//cJ/n4ZZ03cPTD69R133UsOD/f2MuXXMA "05AB1E – 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
```
[Answer]
# 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!](https://tio.run/##K6gsycjPM/6fZhvzPycxNyklUaFCp9JKXdVAK0VdVaNSW6PCxkBTp0Lzf0lqcUlyYnGqgq1CtIahjqGmDpA0ApEGYI6uuY4xkDLQMYCI6RpqxnKl5RcpZOpkKWTmKcD0WykUFGXmlWikaQAlNDX/AwA "Python 3 – Try It Online")
[Answer]
# C#, 56 bytes
[Try it Online!](https://tio.run/##lY9RS8MwFIXf8ysufVnClpHqw6BdKyL4NHGg4oP4cJtlJbCmJckEkf32mraoVRjUQyD3HvLdcyMdl7VV7dFpU8LDu/OqSgkxWCnXoFRwUxtXH9R108Tkg0CQPKBzsLV1abHqncHv5Dx6LeGt1ju4Q22o8zYMfnkFtKVj3@9@iE63RyPX2vjFqBrAPId9sCBrMcuLLKe4FlcRj5IoYnPadxwTZPPQL7e426i9p0VwRVIsZmLG2nSUQ75@s3y22quNNop242nMwoE5RHD/9JhAHLH014LnsYse6ykxGRN/4sREkK8YvRyBXIjVRDREihEp/rEqP7/riRAy3CfSfgI)
```
a=>b=>(a<0?"-":"")+((a<0?-a:a)+"").PadLeft(b<0?0:b,'0')
```
[Answer]
# [Java (OpenJDK 8)](http://openjdk.java.net/), 47 bytes
```
x->y->"".format("%0"+((y<1?1:y)-(x>>31))+"d",x)
```
[Try it online!](https://tio.run/##lc49a8MwEIDh3b/iEBSkphJ2UygkqboVOnTKWDqodhzkyJKwzsGi5Le7Jh8moz3pOD28XKWOiju/s1Vx6HXtXYNQDTvRojaibG2O2lnxuE58@2t0DrlRIcCX0hb@EoDrNqDC4Tk6XUA9/NEtNtruv39ANfvAzhTg0@LHtbi5ny9YSijhre@4jFwSIkrX1AopeUjJgtK4yd6zVWScdlIuM8YWpCBPHevX5/Q2BtzVwrUo/BBDY2kplPcm0oyNA5uOn6fgdE6av970coqed/Z4CZ/CR53OwbPKLxd8Sk79Pw "Java (OpenJDK 8) – Try It Online")
At first I thought, easy, 30 chars max (which is quite short when manipulating strings in Java). Then the exceptions happened.
[Answer]
# JavaScript (ES6), 42
Recursive, parameters in reverse order, first y then x. And [Currying](https://en.wikipedia.org/wiki/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)
})
```
[Answer]
# **[Python 3.6](https://docs.python.org/3/), ~~28~~ 37 bytes**
```
lambda x,y:f'{x:0{(y,0)[y<0]+(x<0)}}'
```
[Try it online!](https://tio.run/##NYvBCoMwEETv/Yq9maUrbPRQCPol6iGthqa0UTSHBPHb01To5Q0zw1uif86uTqbt01t/7qOGQFGZYg@KdxGJsYsND1cRGsbjKJKfNv/Q2wQtdEKSRMqsfuSzlDeqc3A2z62UOFzMvIKlF1gHf1/BslrnhRH5QExf "Python 3 – 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`
[Answer]
# bash, ~~27~~, 25 bytes
-2 bytes thanks to Bruce Forte
```
printf %0$[$2+($1<0)]d $1
```
[try it online](https://tio.run/##S0oszvj/v6AoM68kTUHVQCVaxUhbQ8XQxkAzNkVBxfD///@GBv@NAQ)
[Answer]
# [Husk](https://github.com/barbuz/Husk), 12 bytes
```
Ö±Ωo≥⁰#±:'0s
```
[Try it online!](https://tio.run/##ASMA3P9odXNr///DlsKxzqlv4oml4oGwI8KxOicwc////zX/LTM0MA "Husk – 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.
```
[Answer]
# R, ~~56~~ 48 bytes
```
function(x,y)sprintf(paste0("%0",y+(x<0),"d"),x)
```
[Try it online!](https://tio.run/##XYzRCsIwDEXf/YoQEBJMIVVhL@vHyLSwlzq2Ct3X163bKpi3czg3Y/bgsv@ELvbvQElmnoaxD9HT8JjiSwnPijJfKLXKgk9kSZw9WbEMAM4BWjytfD1YN6GlKIGuwjRy24VRbYqytTHHyCzmN1LR@nZj@8f3ysth/gI "R – Try It Online")
-8 bytes thanks to [djhurio](https://codegolf.stackexchange.com/users/13849/djhurio)
### Explanation
* `sprintf("%0zd",x)` returns `x` as a string padded with zeros to be of length `z`
* `paste0("%0",y+(x<0),"d")` constructs the string `"%0zd"`, where `z` is `y`, plus 1 if `x` is less than zero
* If `z` is less than the number of digits in `x`, `x` is printed as a string as is
[Answer]
# [Japt](https://github.com/ETHproductions/japt/), ~~13~~ 8 bytes
Takes first input (`x`) as a string.
```
®©ùTV}'-
```
[Try it](https://ethproductions.github.io/japt/?v=1.4.5&code=rqn5VFZ9Jy0=&input=Ii04IiwtOA==)
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`.
[Answer]
## [Alice](https://github.com/m-ender/alice), 23 bytes
```
/oRe./'+Ao
\I*tI&0-R$@/
```
[Try it online!](https://tio.run/##S8zJTE79/18/PyhVT19d2zGfK8ZTq8RTzUA3SMVB//9/Q3MuYwA "Alice – 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 `#`.
[Answer]
# C, 33 bytes
```
f(x,y){printf("%0*d",y+(x<0),x);}
```
[Try it online!](https://tio.run/##S9ZNT07@/z9No0KnUrO6oCgzryRNQ0nVQCtFSadSW6PCxkBTp0LTuvY/UEIhNzEzT0OTq5pLAQjSNAx1FAw1rQtKS4o1lJQ0rRGiRlhEDbAq1jXXUTDGIozDaKAhuljEsZuNU9QEyKn9DwA)
[Answer]
# [Charcoal](https://github.com/somebody1234/Charcoal), 16 13 bytes
```
‹Ｎ⁰﹪⁺⁺%0ηd↔Ｉθ
```
[Try it online!](https://tio.run/##S85ILErOT8z5//9Rw873e9Y9atzwfueqR427gEjV4Nz2lEdtU97vWXlux///uuZcxgA "Charcoal – 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
```
* 3 bytes saved thanks to Neil!
[Answer]
## [Retina](https://github.com/m-ender/retina), 39 bytes
```
\d+$
$*0
((\d)*),(?<-2>-0+|0)*(0*)
$3$1
```
[Try it online!](https://tio.run/##FcchDoAwDABA33eUpC1t0m4CQ0DyiQlIhsAgCJK/D3B3134f59Y6WtZWao@A4kBUKgsrzaOlybx/nIVcGDBjtBYaEJog/IMNmsHV/1m8 "Retina – Try It Online")
Input should be comma-separated with the number first and the width second.
[Answer]
# 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](http://sandbox.onlinephpfunctions.com/code/9074bd4d6a0d2f1f5d395c61858c0278663dc242).
[Answer]
# 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!](https://tio.run/##VY2xCoMwFEX3foaBopDQmA4d9EmGLoKD0G6SIbRJjKAFfZM/n6aloB0uj8O7nDtq7M2o0T90sBDSAe6vG85@ckVtOyJK4HSQhEZIV6gnNM7MjZkc9pJkFRBBEdYYIlSxwHCSrX42xmL3616987hEA6qvsYrCJCmrhSbsc5TKjqGNgyhtl9NcHTYQO@D7F7vQ80ac8r8iy1V4Aw "Wolfram Language (Mathematica) – Try It Online")
[Answer]
# Mathematica, ~~63~~ 62 bytes
```
If[#<0,"-",""]<>IntegerString[#,10,Max[#2,IntegerLength@#,1]]&
```
[Try it online!](https://tio.run/##TYuxCsMgFEX3fMVDIdMLaJrSoWlxDTRQ6CgOUtRkiJTgUAh@u3WoJNu595676DCZRYf5rZO9pcFK2jMkDUFCVH8ffDDOrK@wzt5JipzhqL@StvhfHsa7MIm8KFWnUX/kM6tBWiGoqhG2CgA2jsAjFmwLsr1uLginwkc9O00JmdmOh7Yrz3O2u1hFdU0/ "Wolfram Language (Mathematica) – Try It Online")
[Answer]
# 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)))
```
[Answer]
# [Octave](https://www.gnu.org/software/octave/), 44 bytes
```
@(x,y)fprintf(['%0',num2str(y+(x<0)),'d'],x)
```
[Try it online!](https://tio.run/##y08uSSxL/Z9mq6en999Bo0KnUjOtoCgzryRNI1pd1UBdJ68016i4pEijUlujwsZAU1NHPUU9VqdC83@ahqGOkSYXVLF6TJ66Jleahq65jjGGoKGBjqHmfwA "Octave – Try It Online")
[Answer]
# [Haskell](https://www.haskell.org/), 54 bytes
```
x#y|s<-show$abs$x=['-'|x<0]++('0'<$[length s+1..y])++s
```
[Try it online!](https://tio.run/##y0gszk7Nyfn/v0K5sqbYRrc4I79cJTGpWKXCNlpdV72mwsYgVltbQ91A3UYlOic1L70kQ6FY21BPrzJWU1u7@H9uYmaegq1CSj6XAhAUlJYElxT55CmoKBgqKCsYYhM0whA0wKZUQ9dcEyhujC4OUmyA1QgNXUPN/wA "Haskell – Try It Online")
[Answer]
# [Ruby](https://www.ruby-lang.org/), ~~31~~ 28 bytes
Thanks [Carl](https://codegolf.stackexchange.com/questions/149620/the-leading-zeroes-challenge/149657?noredirect=1#comment365719_149657) for saving 3 bytes using interpolation.
```
->x,y{"%0#{y+(x<0?1:0)}d"%x}
```
[Try it online!](https://tio.run/##KypNqvyfZvtf165Cp7JaSdVAubpSW6PCxsDe0MpAszZFSbWi9n9BaUmxQlq0oY5BLBeUbaBjCmcb6hgiJHQNDXSMY/8DAA "Ruby – Try It Online")
[Answer]
# [Japt](https://github.com/ETHproductions/japt), ~~14~~ 12 bytes
*Saved 2 bytes thanks to @ETHproductions*
```
s r"%d+"_ù0V
```
[Try it online](https://ethproductions.github.io/japt/?v=1.4.5&code=cyByIiVkKyJf+TBW&input=LTcsMw==)
[Answer]
# [PowerShell](https://github.com/TryItOnline/TioSetup/wiki/Powershell), ~~25~~ 40 bytes
```
param($a,$b)$a|% *g $("D$b"*($b|% *o 0))
```
[Try it online!](https://tio.run/##K8gvTy0qzkjNyfn/vyCxKDFXQyVRRyVJUyWxRlVBK11BRUPJRSVJSUtDJQkkkK9goKn5//9/DV1jc00gaaoJAA "PowerShell – 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.
[Answer]
# 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)));
```
[Answer]
# [Clean](https://clean.cs.ru.nl), ~~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!](https://tio.run/##Dcy7CsIwFADQ3a@4ZImlBAoOgqTSQQfBLaNxCGlT0uYhSSoN4q8bO57lSDMIV6zvFzOAFdoVbV8@JGCpv7r3rlsht1rtM20qRBBCdV1/NsszJriSuMGcS0rCtMSkVYb1MXM@U3JKnqWg3Qj5@S0sia1soYMDkGP5SWXEGAu53cslO2G1jH8 "Clean – Try It Online")
[Answer]
# [C (gcc)](https://gcc.gnu.org/), 45 bytes
```
f(x,y){printf("%s%0*i","-"+(x>=0),y,abs(x));}
```
[Try it online!](https://tio.run/##bc7BCsIwDIDhu09RAoNEU0hV8FD0XWah0oNj2A06xp69luFhuOb48YfE6ZdzOXtMPNHcf0I3eIQmNnIMwKDhhOlxF@KJ22fERGSXXCL1bkOHpOaDR8OGrCrTj0NEALIrnisov3SL@saXPZpKWdb1qlsUlv0hqb0kfP3HJX8B "C (gcc) – 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 `0`s. `y` denotes this number. We pad `abs(x)` to avoid the negative in some arguments.
[Answer]
## Perl, 25 + `-n` flag = 26 bytes
```
printf"%0*d",<>+($_<0),$_
```
[Try it online!](https://tio.run/##K0gtyjH9/7@gKDOvJE1J1UArRUnHxk5bQyXexkBTRyX@/39dcy7jf/kFJZn5ecX/dfMA "Perl 5 – Try It Online")
[Answer]
# Perl 5, 22 + 1 (-`n`) = 23 bytes
```
printf"%0*d",<>+/-/,$_
```
[Try it online](https://tio.run/##K0gtyjH9/7@gKDOvJE1J1UArhUtJx8ZOW19XX0cl/v9/Qy4QNOIyNABSuuZcxly6YCEDEG0AhiDa5F9@QUlmfl7xf908AA)
]