如何将 100.00 转换为 100 和 100.23 转换为 100.23 飞镖

How to convert 100.00 to 100 and 100.23 to 100.23 dart

如何将 100.00 或 100.0 转换为 100,如果数字为 100.23,则应保持为相同的 100.23。

在 dart 中,我测试了这些函数 floor() 和 round() 它们 return 100 即使数字是 100.23。

如何解决?

谢谢

在您得到更好的答案之前,您可以执行类似以下步骤的操作:

double value = 100.32739273;
String formattedValue = value.toStringAsFixed(2);

print(formattedValue);

if (formattedValue.endsWith(".00")) {
  formattedValue = formattedValue.replaceAll(".00", "");
}

print(formattedValue);

利用flutter的intl包对数字进行格式化。请参考以下内容

import 'package:intl/intl.dart' as intl;

  @override
  void initState() {
    var valueFormat = intl.NumberFormat.decimalPattern();
    print(valueFormat.format(100.234));
    print(valueFormat.format(100.00));
  }

输出

I/flutter ( 5364): 100.234
I/flutter ( 5364): 100
double input1 = 100.00;  //100
double input2 = 100.0; //100
double input3 = 100.23; //100.23

RegExp regex = RegExp(r"([.]*0)(?!.*\d)");

String str = input1.toString().replaceAll(RegExp(r"([.]*0)(?!.*\d)"), "");