Logo

Programming-Idioms

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

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%"

const percentFormatter = new Intl.NumberFormat('en-US', {
  style: 'percent',
  maximumSignificantDigits: 3
});

const s = percentFormatter.format(x);

Uses an Intl.NumberFormat to create a human-readable percentage string.
const s = Math.round (x * 1000) / 10 + '%'

Sadly there's no builtin in JavaScript for this sort of thing.
#include <stdio.h>
char s[7];
sprintf(s, "%.2lf%%", x * 100);

New implementation...