Reputation: 321
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 %
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;
}
Upvotes: 1
Views: 2936
Reputation: 3150
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
Upvotes: 2