[英]How to localize percentage values in Dart/Flutter correctly?
我仍在寻找一种更好的方法来本地化 Dart/Flutter 中的百分比值。 到目前为止,我只是使用以下代码将百分比值转换为合适的字符串: '${(_percentage * 100).toStringAsFixed(3)}%'
对于例如 65.7893 的百分比值,您会得到以下字符串: 65.789%
。 这对英语很好,但不适用于其他语言。
例如,对于德语,字符串应如下所示: 65,789 %
感谢有用的提示,我现在创建了以下包装器 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;
}
首先将 intl package 添加到您的 pubspec.yaml
使用本地化和 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));
您可以在此处参考支持的语言环境: https://www.woolha.com/tutorials/dart-formatting-currency-with-numberformat#supported-locales
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.