Formatting percentage values with JavaScript Intl

Jan 5, 2021

Javascript contains an Internationalisation API that you can use to format numbers to a user's locale. Setting the style to percent is all that is needed.

1Intl.NumberFormat("en-GB", { style: "percent"}).format(1.2345); // => "123%" Note: A value of 1 will return 100% because 1x anything is 100%!

To specify the decimal places use minimumFractionDigits and maximumFractionDigits to give you more visual control.

1Intl.NumberFormat("en-GB", { 2 style: "percent", 3 minimumFractionDigits: 1, 4 maximumFractionDigits: 2 5}).format(123.45); // => "123.45%"

This can all be wrapped in a function to save repetition and keep consistency across your app.

1const formatPercentage = (value, locale = "en-GB") => { 2 return Intl.NumberFormat(locale, { 3 style: "percent", 4 minimumFractionDigits: 1, 5 maximumFractionDigits: 2 6 }).format(value); 7}; 8 9formatPercentage(1); // => "100.0%" 10formatPercentage(0.1); // => "10.0%" 11formatPercentage(0.13); // => "13.0%" 12formatPercentage(0.135); // => "13.5%" 13formatPercentage(0.1357); // => "13.57%" 14formatPercentage(0.13579); // => "13.58%"