How to localize percentage values in Dart/Flutter correctly?
591
First add intl package into your pubspec.yaml
Use the Localisation and NumberFormat class.
Locale myLocale = Localizations.localeOf(context); /* gets the locale based on system language*/
String languageCode = myLocale.languageCode;
print(NumberFormat.percentPattern(languageCode).format (60.23));
You can refer here for the the supported locales : https://www.woolha.com/tutorials/dart-formatting-currency-with-numberformat#supported-locales
Author by
Dark Purple Knight
Updated on December 30, 2022Comments
-
Dark Purple Knight over 1 year
I am still looking for a better way to localize a percentage value in Dart/Flutter. So far, I'm just converting a percentage value to a suitable string with the following code:
'${(_percentage * 100).toStringAsFixed(3)}%'
For a percentage value of e.g. 65.7893 you get the following string:
65.789%
. That's fine for English, but not for other languages.For example, for German, the string should be as follows:
65,789 %
Solution
Thanks to the useful tips, I have now created the following wrapper function.
import 'package:flutter/material.dart'; import 'package:intl/intl.dart'; _generatePercentString(percentValue) { var systemLocale = Localizations.localeOf(context); var numberFormatter = NumberFormat.decimalPercentPattern( locale: systemLocale.languageCode, decimalDigits: 3, ); var percentString = numberFormatter.format(percentValue); return percentString; }
-
jamesdlin almost 3 yearsDoes
NumberFormat
(specifically,NumberFormat.percentPattern
) frompackage:intl
not do what you want? -
Dark Purple Knight almost 3 years
NumberFormat.percentPattern
requires alocale
string, although I only want to use the system language. -
jamesdlin almost 3 yearsThe locale argument is optional. I presume it uses the current locale if not specified.
-
Dark Purple Knight almost 3 yearsIn my tests with different locals, the generated strings were always appropriate for English.
-
jamesdlin almost 3 yearsIf that's the case, then you could pretty trivially create a wrapper function or extension method that automatically calls it with the current locale.
-
Dark Purple Knight almost 3 yearsThat would be an easy solution to implement. I guess there is no simpler solution with even less code.
-
-
Dark Purple Knight almost 3 yearsI would like to avoid specifying a
locale
string for each percentage value, because the formatting should only match the system language. -
Niteesh almost 3 yearsI've updated the answer to solve your query.
-
Dark Purple Knight almost 3 yearsI will create a wrapper function for it.
-
Dark Purple Knight almost 3 years
languageCode
is a getter. -
Niteesh almost 3 yearsSorry, It was a mistake, my bad, it's a property