Logo

Programming-Idioms

  • Pascal
  • VB
  • Lua
  • Java
  • Erlang

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 = io_lib:format("~.2f", [X]).

S will be an iolist(), technically not a string() but it's good enough for most purposes and you can always use iolist_to_binary/1
uses SysUtils;
s := format('%.2f',[ x]);
s = string.format("%.2f",x)
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);
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);
String s = String.format("%.2f", x);
#include <stdio.h>
sprintf(s, "%.2f", x);

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