View Problem

Zero pad a number

Given the number 42, pad it to 8 characters like 00000042
DiskEdit
ruby
42.to_s.rjust(8,"0")
DiskEdit
ruby
"%08d" % 42
ExpandDiskEdit
java
String formatted = new DecimalFormat("00000000").format(42);
ExpandDiskEdit
java 1.5 or later
String formatted = String.format("%08d", 42);
DiskEdit
perl
sprintf("%08d", 42);
ExpandDiskEdit
groovy
formatted = new DecimalFormat('00000000').format(42)
ExpandDiskEdit
groovy
formatted = 42.toString().padLeft(8, '0')
ExpandDiskEdit
groovy
// to stdout
printf "%08d\n", 42
// to a string
formatted = sprintf("%08d", 42)
ExpandDiskEdit
groovy
formatted = String.format("%08d", 42)
ExpandDiskEdit
scala
val formatted = String.format("%08d", int2Integer(42))
ExpandDiskEdit
scala
printf("%08d\n", 42)
ExpandDiskEdit
scala 2.9.0.1
println("%08d".format(42))
ExpandDiskEdit
scala 2.10.0

val num = 42
println(f"$num%08d")
ExpandDiskEdit
scala 2.10.0
println(f"${42}%08d")
DiskEdit
python
"%08d" % 42
ExpandDiskEdit
cpp C++/CLI .NET 2.0
String^ formatted = Convert::ToString(42)->PadLeft(8, '0');
ExpandDiskEdit
cpp C++/CLI .NET 2.0
String^ formatted = String::Format("{0,8:D8}", 42);
ExpandDiskEdit
cpp
std::printf("%08d", 42);
ExpandDiskEdit
cpp
std::ostringstream os;
os << std::setw(8) << std::setfill('0') << 42 << std::ends;
std::cout << os.str() << std::endl;
ExpandDiskEdit
cpp
std::cout << boost::format("%|08|") % 42 << std::endl;
ExpandDiskEdit
fsharp
printfn "%08d" 42
ExpandDiskEdit
fsharp
let formatted = sprintf "%08d" 42
printfn "%s" formatted
ExpandDiskEdit
fsharp
let buffer = new StringBuilder()
Printf.bprintf buffer "%08d" 42
printfn "%s" (buffer.ToString())
ExpandDiskEdit
fsharp
let formatted = String.Format("{0,8:D8}", 42)
Console.WriteLine(formatted)
ExpandDiskEdit
fsharp
let formatted = Convert.ToString(42).PadLeft(8, '0')
Console.WriteLine(formatted)
ExpandDiskEdit
erlang
Formatted = io_lib:format("~8..0B", [42]),
ExpandDiskEdit
erlang
io:format("~8..0B~n", [42]).
DiskEdit
ocaml
Printf.printf "%08d" 42;;
DiskEdit
ocaml
let s = Printf.sprintf "%08d" 42 in
print_string s;;
DiskEdit
csharp
string.Format("{0,8:D8}", 42);
ExpandDiskEdit
php
echo str_pad(42, 8, 0, STR_PAD_LEFT);
ExpandDiskEdit
php
printf("%08d", 42);
DiskEdit
haskell
import Text.Printf

printf "%08d" 42
DiskEdit
clojure clojure
(defn pad
([x] (if (> 8 (.length (str x))) (pad (str 0 x)) (str x)))
)
DiskEdit
clojure clojure
(defn pad [x]
(format "%08d" x))
DiskEdit
clojure
(format "%08d" 42)
ExpandDiskEdit
fantom
formatted := 42.toStr.padl(8, '0')
ExpandDiskEdit
fantom
formatted := 42.toLocale("00000000")
ExpandDiskEdit
go
fmt.Printf("%08d", 42)

Submit a new solution for ruby, java, perl, groovy ...