formatPercent function
Formats a percentage value for locale in pure Dart.
Accepts ratio fractions between -1.0 and 1.0 (e.g. 0.42 becomes 42%) as well
as whole percentage numbers (e.g. 42 becomes 42%). Includes appropriate locale spacing
before the % symbol for languages such as French, German, Russian, and Swedish.
When locale is omitted, defaults to the active BloomI18n.instance.locale value.
formatPercent(0.42, locale: 'en-US'); // "42%"
formatPercent(0.42, locale: 'fr-FR'); // "42 %"
See also:
- formatNumber, the underlying number formatter.
- formatCurrency, for currency formatting.
Implementation
String formatPercent(
num value, {
String? locale,
int? decimalDigits = 0,
}) {
final intlLocale =
(locale ?? BloomI18n.instance.locale.value).replaceAll('-', '_');
final percentValue = value <= 1.0 && value >= -1.0 ? value : value / 100;
try {
return intl.NumberFormat.decimalPercentPattern(
locale: intlLocale, decimalDigits: decimalDigits)
.format(percentValue);
} catch (_) {
// Fall back to the small built-in formatter for an unknown locale.
}
final loc = (locale ?? BloomI18n.instance.locale.value)
.replaceAll('_', '-')
.toLowerCase();
final lang = loc.split('-').first;
final fallbackPercentValue =
value <= 1.0 && value >= -1.0 ? value * 100 : value;
final numStr = formatNumber(fallbackPercentValue,
locale: locale, decimalDigits: decimalDigits);
if (['fr', 'de', 'ru', 'sv', 'pl', 'fi', 'no', 'cs'].contains(lang)) {
return '$numStr %';
}
return '$numStr%';
}