Logo

Programming-Idioms

  • Java
  • Python

Idiom #65 Format decimal number

From the real value x in [0,1], create its percentage string representation s with one digit after decimal point. E.g. 0.15625 -> "15.6%"

s = f"{x:.01%}"
s = format(x, '.1%')
s = '%.1f%%' % (x * 100)
s = '{:.1%}'.format(x)

.1 means only one digit after decimal point.
% handles the "multiplication" and shows the percentage sign.
import static java.math.RoundingMode.HALF_UP;
import static java.text.NumberFormat.getPercentInstance;
import java.text.NumberFormat;
NumberFormat f = getPercentInstance();
f.setMaximumFractionDigits(1);
f.setRoundingMode(HALF_UP);
String s = f.format(x);
import java.text.DecimalFormat;
String s = new DecimalFormat("0.0%").format(x);

This notation handles the multiplication by 100 for you.
import static java.text.MessageFormat.format;
String s = format("{0,number,0.0%}", x);
String s = "%.1f%%".formatted(x * 100);
#include <stdio.h>
char s[7];
sprintf(s, "%.2lf%%", x * 100);

New implementation...