Logo

Programming-Idioms

  • Java
  • Js

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.

num.toFixed(2)
String 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);
#include <stdio.h>
sprintf(s, "%.2f", x);

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