繁体   English   中英

如何隐藏十进制值 = 0

[英]How to hide decimal value when it is = 0

我目前正在尝试使用 Flutter 中的小部件呈现产品的价格值。为此,我传递 state 并将其呈现在相应小部件的参数中。 我需要实现的是隐藏我的 Double 类型 priceValue 的 2 位小数,并在它们为 .= 为 0 时显示它们。

像这样,如果 state.priceValue = 12.00 $ => 应该显示 12 如果 state.priceValue = 12.30 $ => 应该显示 12.30

String removeZero(double money) {
  var response = money.toString();

  if (money.toString().split(".").length > 0) {
    var decmialPoint = money.toString().split(".")[1];
    if (decmialPoint == "0") {
      response = response.split(".0").join("");
    }
    if (decmialPoint == "00") {
      response = response.split(".00").join("");
    }
  }

  return response;
}

编辑:我添加检查字符串是否包含小数点以避免索引越界问题

尝试这个:

String price = "12.00$"

print(price.replaceAll(".00", ""));

或参考: 如何使用 Dart 删除尾随零

double num = 12.50; // 12.5
double num2 = 12.0; // 12
double num3 = 1000; // 1000

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

String s = num.toString().replaceAll(regex, '');

但是第二个选项将删除所有尾随零,因此12.30将改为12.3

您好,您可以使用这样的扩展名:

extension myExtension on double{
 String get toStringV2{
  final intPart = truncate();
  if(this-intPart ==0){
   return '$intPart';
  }else{
   return '$this';
  }
 }
}

要使用扩展:

void main() {
 double numberWithDecimals = 10.8;
 double numberWithoutDecimals = 10.00;
 //print
 print(numberWithDecimals.toStringV2);
 print(numberWithoutDecimals.toStringV2);
}

暂无
暂无

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

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