Logo

Programming-Idioms

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

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

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

s = string.format("%.2f",x)
#include <stdio.h>
sprintf(s, "%.2f", x);
#include <format>
auto s = std::format("{.2f}", x);
#include <charconv>
#include <array>
std::array<char, 23> buffer;
std::string s{};
if (auto [ptr, ec] = std::to_chars(buffer.data(), buffer.data() + buffer.size(), x, std::chars_format::fixed, 2); ec == std::errc{}) {
  s = std::string(buffer.data(), ptr);
} else {
  s = std::make_error_code(ec).message();
}
#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 ""
num.toFixed(2)
import static java.math.RoundingMode.HALF_UP;
import static java.text.NumberFormat.getNumberInstance;
import java.text.NumberFormat;
NumberFormat f = getNumberInstance();
f.setRoundingMode(HALF_UP);
f.setMaximumFractionDigits(2);
String s = f.format(x);
String s = String.format("%.2f", x);
import java.math.BigDecimal;
BigDecimal d = new BigDecimal(x);
String s = "%.2f".formatted(d);
import static java.math.RoundingMode.HALF_UP;
import java.math.BigDecimal;
import java.math.MathContext;
MathContext m = new MathContext(3, HALF_UP);
BigDecimal d = new BigDecimal(x, m);
String s = d.toPlainString();
String s = "%.2f".formatted(x);
s = "%.2f".format(x)
$s = sprintf('%.2f', $x);
uses SysUtils;
s := format('%.2f',[ x]);
$s = sprintf "%.2f", $x;
s = f'{x:.2f}'
s =  '{:.2f}'.format(x)
s = "%.2f" % x
let s = format!("{:.2}", x);

New implementation...
< >
programming-idioms.org