简体   繁体   English

Flutter/Dart - 将双精度格式格式化为带有千位分隔符和小数点后数字的字符串

[英]Flutter/Dart - Format double to String with thousand separators AND digits after decimal point

I am trying to achieve a formatted String from a double variable, which will include thousand separators (",") AND will include always 2 digits after the decimal point (even if it's zero).我正在尝试从双精度变量获得格式化的字符串,它将包含千位分隔符 (",") 并且将始终包含小数点后的 2 位数字(即使它为零)。

I've succeeded to achieve both of them separately, but couldn't achieve them combined together.我已经成功地分别实现了它们,但无法将它们组合在一起。

Example for what I'm looking to achieve:我想要实现的目标示例:

100 => "100.00"
100.5 => "100.50"
1000 = "1,000.00"
1000.5 = > "1,000.50"
1000000 => "1,000,000.00"
1000000.53 => 1,000,000.53
etc...

I've tried to achieve this using:我尝试使用以下方法实现此目的:

NumberFormat.decimalPattern('en').format(
    double.parse(
        myDoubleVar.toStringAsFixed(2),
    ),
);

But it doesn't give my the decimal points if they are zero.但如果它们为零,它不会给我小数点。

Does anyone know how can I achieve this?有谁知道我怎样才能做到这一点?

Thank you谢谢

Try with this试试这个

double amount = 1000000;
NumberFormat numberFormat = NumberFormat("#,##0.00", "en_US");

print('${(numberFormat.format(amount))}');

output: 1,000,000.00 output:1,000,000.00

Here I have used like this.这里我是这样用的。

void main() {
  
  num balance = 120000;
    print("\$${balance.toStringAsFixed(2).replaceAllMapped(RegExp(r'(\d{1,3})(?=(\d{3})+(?!\d))'), (Match m) => "${m[1]},") }");
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM