Format Percentage for Display in JavaScript

Input Output
0.12 12%
0.0012345 0.12%
0.0 0

2 significant digits but locale-sensitive, strip meaningless trailing zeroes and decimal dividers.

const formatPercentage = function (value) {
    return new Intl.NumberFormat(
        undefined, // use browser locale
        // Choose the options that get us closest to our desired style – a percentage that tells you enough to be useful but no unnecessary decimal places or trailing zeroes.
        {
            style: "percent", // Treat decimals as percentages, multiplying by 100 and adding a % sign.
            minimumSignificantDigits: 2,
            maximumSignificantDigits: 2
        }
    )
        .format(value)
        // \D here is the locale-agnostic decimals separator.
        .replace(/(\D[0-9]*?)0+%$/, "$1%") // Get rid of trailing zeroes after the decimal separator.
        .replace(/\D%/, "%") // Clean up the scenario where we got rid of everything after the decimal separator and now have something like "4.%.
        .replace(/^0%$/, "0"); // Replace literal "0%" with "0" as zero is unitless.
};

Leave a Reply

Your email address will not be published. Required fields are marked *

This site is protected by reCAPTCHA and the Google Privacy Policy and Terms of Service apply.