View Problem

Format a decimal number

Format the number 7/8 as a decimal with 2 places: 0.88
DiskEdit
ruby
(7.0/8.0*100).round/100.0
DiskEdit
ruby 1.9+
(7.0/8.0).round(2)
ExpandDiskEdit
java 1.5 or later
String formatted = String.format("%3.2f", 7./8.);
DiskEdit
perl
sprintf("%.2f", 7/8);
ExpandDiskEdit
groovy
def result = 7/8
println result.round(new MathContext(2))
ExpandDiskEdit
groovy
def result = 7/8
printf "%.2g", result
DiskEdit
groovy 1.6.4
new Double(7/8).round(2)
ExpandDiskEdit
scala
val formatted = String.format("%3.2f", double2Double(7./8.))
ExpandDiskEdit
scala
printf("%3.2f\n", 7./8.)
DiskEdit
python
"%.2f" % (7 / 8.0)
DiskEdit
python
round(7./8., 2)
ExpandDiskEdit
cpp C++/CLI .NET 2.0
String^ formatted = String::Format("{0,3:F2}", result);
ExpandDiskEdit
cpp C++/CLI .NET 2.0
Console::WriteLine("{0,3:F2}", (7. / 8.));
ExpandDiskEdit
cpp
std::printf("%3.2f\n", result);
ExpandDiskEdit
cpp
std::ostringstream os;
os.width(3); os.fill('0'); os.setf(std::ios::fixed|std::ios::showpoint); os.precision(2);
os << result << std::ends;
std::cout << os.str() << std::endl;
ExpandDiskEdit
cpp
std::cout << boost::format("%|3.2f|") % result << std::endl;
ExpandDiskEdit
fsharp
printfn "%3.2f" (0.7 / 0.8)
ExpandDiskEdit
fsharp
let formatted = String.Format("{0,3:F2}", (0.7 / 0.8))
Console.WriteLine(formatted)
ExpandDiskEdit
erlang
Formatted = io_lib:format("~.2f", [7/8]),
ExpandDiskEdit
erlang
io:format("~.2f~n", [7/8]).
DiskEdit
ocaml
Printf.printf "%4.2f" (7. /. 8.);;
DiskEdit
ocaml
let s = Printf.sprintf "%4.2f" (7. /. 8.) in
print_string s;;
DiskEdit
csharp
public class FormatDecimal {
public static void Main() {
decimal result = decimal.Round( 7 / 8m, 2);
System.Console.WriteLine(result);
}
}
ExpandDiskEdit
php
printf("%.2g", 7/8);
ExpandDiskEdit
php
echo round(7/8, 2);
DiskEdit
haskell
import Text.Printf

printf "%3.2f" (7/8)
DiskEdit
haskell
main = putStrLn $ Numeric.showFFloat (Just 2) (7/8) ""
DiskEdit
clojure
(format "%3.2f" (/ 7.0 8))
DiskEdit
clojure
(* 0.01 (Math/round (* 100 (float (/ 7 8)))))
ExpandDiskEdit
fantom
formatted := (7.0/8.0).toLocale("0.00")
ExpandDiskEdit
go
fmt.Printf("%.2f", 7.0 / 8.0)

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