This language bar is your friend. Select your favorite languages!

Idiom #23 Convert real number to string with 2 decimal places

Given real number x, create its string representation s with 2 decimal digits following the dot.

#include <stdio.h>
sprintf(s, "%.2f", x);
#include <iomanip>
#include <sstream>
std::stringstream ss;
ss << std::fixed << std::setprecision(2) << x;
s = ss.str();
string s = $"{x:F2}";
import std.string;
string str = format("%.2s", x);
var s = x.toStringAsFixed(2);
s = Float.to_string(x, decimals: 2)
S = io_lib:format("~.2f", [X]).
  write (unit=s,fmt="(F20.2)") x
import "fmt"
s := fmt.Sprintf("%.2f", x)
s <- showFFloat (Just 2) x ""
String s = String.format("%.2f", x);
s = string.format("%.2f",x)
$s = sprintf('%.2f', $x);
s := format('%.2f',[ x]);
$s = sprintf "%.2f", $x;
s = f'{x:.2f}'
s =  '{:.2f}'.format(x)
s = "%.2f" % x
let s = format!("{:.2}", x);

Do you know the best way to do this in your language ?
New implementation...

Idiom created by

Related idioms