最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

flutter - Getting this FormatException: Invalid double when parsing a string to double - Stack Overflow

programmeradmin1浏览0评论

I am trying to convert a string to a double by using the double.parse() method. When I use this, I am getting this error:

FormatException: Invalid double

This is the value of salePriceController.text: $4,249,000.00

Here is the code for what I am doing:

class CommissionCalculatorPopup {
  static void showCommissionCalculator(BuildContext context, double salePrice) {
    showDialog(
      context: context,
      builder: (BuildContext context) {
        return CommissionCalculatorDialog(salePrice: salePrice);
      },
    );
  }
}

class CommissionCalculatorDialog extends StatefulWidget {
  final double salePrice;

  const CommissionCalculatorDialog({required this.salePrice, super.key});

  @override
  State<CommissionCalculatorDialog> createState() =>
      _CommissionCalculatorDialogState();
}

class _CommissionCalculatorDialogState
    extends State<CommissionCalculatorDialog> {
  TextEditingController salePriceController = TextEditingController();
  TextEditingController commissionRateController = TextEditingController();
  double commission = 0.0;

  final NumberFormat currencyFormatter = NumberFormat.currency(symbol: '\$');
  String _formatCurrency(String textCurrency) {

    /// Format the contract price
    String numericCurrency = textCurrency.replaceAll(RegExp(r'[^\d]'), '');
    if (numericCurrency.isNotEmpty) {
      double value = double.parse(numericCurrency);
      String formattedText = currencyFormatter.format(value);
      if (formattedText != null) {
        return formattedText;
      } else {
        return "\$0.00";
      }
    } else {
      return "\$0.00";
    }
  }

  @override
  void initState() {
    super.initState();
    salePriceController.text = _formatCurrency(widget.salePrice.toString());
  }

  @override
  Widget build(BuildContext context) {
    return AlertDialog(
      title: Text(
        'Commission Calculator',
        style: TextStyle(fontSize: 8.sp),
      ),
      content: Column(
        mainAxisSize: MainAxisSize.min,
        children: [
          TextField(
            controller: salePriceController,
            decoration: const InputDecoration(labelText: 'Sale Price (\$)'),
            keyboardType: TextInputType.number,
          ),
          TextField(
            controller: commissionRateController,
            decoration: const InputDecoration(labelText: 'Commission Rate (%)'),
            keyboardType: TextInputType.number,
          ),
          SizedBox(height: 20.sp),
          ElevatedButton(
            onPressed: calculateCommission,
            child: const Text('Calculate Commission'),
          ),
          SizedBox(height: 20.sp),
          Text(
            //'Commission: $_formatCurrency(commission.toString())',
            'Commission: \$${commission.toStringAsFixed(2)}',
            style: TextStyle(fontSize: 8.sp),
          ),
        ],
      ),
      actions: [
        TextButton(
          onPressed: () {
            Navigator.of(context).pop();
          },
          child: const Text('Close'),
        ),
      ],
    );
  }

  void calculateCommission() {
    if (salePriceController.text.isNotEmpty &&
        commissionRateController.text.isNotEmpty) {
      try {
        double salePrice = double.parse(salePriceController.text) ?? 0.0; <<<< ERROR HERE
        double commissionRate = double.parse(commissionRateController.text) ?? 0.0;

        double commissionAmount = (salePrice * commissionRate) / 100;
        setState(() {
          commission = commissionAmount;
        });
      } catch (e) {
        print(e);
      }
    } else {
      // Handle empty fields
      // You can show an error message or take appropriate action
    }
  }
}

The error occurs in the calculateCommission method. I am not sure why this is happening but I think it has to do with the original assignment of salePriceController but I am just not seeing the issue.

Thanks for your help.

I am trying to convert a string to a double by using the double.parse() method. When I use this, I am getting this error:

FormatException: Invalid double

This is the value of salePriceController.text: $4,249,000.00

Here is the code for what I am doing:

class CommissionCalculatorPopup {
  static void showCommissionCalculator(BuildContext context, double salePrice) {
    showDialog(
      context: context,
      builder: (BuildContext context) {
        return CommissionCalculatorDialog(salePrice: salePrice);
      },
    );
  }
}

class CommissionCalculatorDialog extends StatefulWidget {
  final double salePrice;

  const CommissionCalculatorDialog({required this.salePrice, super.key});

  @override
  State<CommissionCalculatorDialog> createState() =>
      _CommissionCalculatorDialogState();
}

class _CommissionCalculatorDialogState
    extends State<CommissionCalculatorDialog> {
  TextEditingController salePriceController = TextEditingController();
  TextEditingController commissionRateController = TextEditingController();
  double commission = 0.0;

  final NumberFormat currencyFormatter = NumberFormat.currency(symbol: '\$');
  String _formatCurrency(String textCurrency) {

    /// Format the contract price
    String numericCurrency = textCurrency.replaceAll(RegExp(r'[^\d]'), '');
    if (numericCurrency.isNotEmpty) {
      double value = double.parse(numericCurrency);
      String formattedText = currencyFormatter.format(value);
      if (formattedText != null) {
        return formattedText;
      } else {
        return "\$0.00";
      }
    } else {
      return "\$0.00";
    }
  }

  @override
  void initState() {
    super.initState();
    salePriceController.text = _formatCurrency(widget.salePrice.toString());
  }

  @override
  Widget build(BuildContext context) {
    return AlertDialog(
      title: Text(
        'Commission Calculator',
        style: TextStyle(fontSize: 8.sp),
      ),
      content: Column(
        mainAxisSize: MainAxisSize.min,
        children: [
          TextField(
            controller: salePriceController,
            decoration: const InputDecoration(labelText: 'Sale Price (\$)'),
            keyboardType: TextInputType.number,
          ),
          TextField(
            controller: commissionRateController,
            decoration: const InputDecoration(labelText: 'Commission Rate (%)'),
            keyboardType: TextInputType.number,
          ),
          SizedBox(height: 20.sp),
          ElevatedButton(
            onPressed: calculateCommission,
            child: const Text('Calculate Commission'),
          ),
          SizedBox(height: 20.sp),
          Text(
            //'Commission: $_formatCurrency(commission.toString())',
            'Commission: \$${commission.toStringAsFixed(2)}',
            style: TextStyle(fontSize: 8.sp),
          ),
        ],
      ),
      actions: [
        TextButton(
          onPressed: () {
            Navigator.of(context).pop();
          },
          child: const Text('Close'),
        ),
      ],
    );
  }

  void calculateCommission() {
    if (salePriceController.text.isNotEmpty &&
        commissionRateController.text.isNotEmpty) {
      try {
        double salePrice = double.parse(salePriceController.text) ?? 0.0; <<<< ERROR HERE
        double commissionRate = double.parse(commissionRateController.text) ?? 0.0;

        double commissionAmount = (salePrice * commissionRate) / 100;
        setState(() {
          commission = commissionAmount;
        });
      } catch (e) {
        print(e);
      }
    } else {
      // Handle empty fields
      // You can show an error message or take appropriate action
    }
  }
}

The error occurs in the calculateCommission method. I am not sure why this is happening but I think it has to do with the original assignment of salePriceController but I am just not seeing the issue.

Thanks for your help.

Share Improve this question asked Nov 20, 2024 at 17:53 LostTexanLostTexan 89112 silver badges28 bronze badges 3
  • 2 The $ and , are not valid in the normal string representations of doubles. Since you use NumberFormat.format to generate the string, you should be using NumberFormat.parse when reading it back. – jamesdlin Commented Nov 20, 2024 at 20:00
  • 1 Yep, your calculator is working fine. But is not accepting number like 3,200.00. So you need to Show numbers like that but use in calculations numbers like 3200.00. You can use String.replace(",", ""); – Alexandre B. Commented Nov 20, 2024 at 20:02
  • Thanks for your comments. I was able to fix it because I had a type mismatch with the variable "commission". – LostTexan Commented Nov 20, 2024 at 21:44
Add a comment  | 

2 Answers 2

Reset to default 0

You need to declare it in your code:

 late String _workingValue; 

And inside your calculateCommission()

      void calculateCommission() {  
    
        if (salePriceController.text.isNotEmpty &&
            commissionRateController.text.isNotEmpty) {
          try {
    
            _workingValue = salePriceController.text.toString().replaceAll(',', '');
    
            double salePrice = double.parse(_workingValue);//double.parse(salePriceController.text) ?? 0.0; //<<<< ERROR HERE
            double commissionRate = double.parse(commissionRateController.text) ?? 0.0;
    
            double commissionAmount = (salePrice * commissionRate) / 100;
            setState(() {
              commission = commissionAmount;
            });
          }catch (e){
    
          }
    
          }
        }

Do the samething if you will earn commissions greater than 1000.

发布评论

评论列表(0)

  1. 暂无评论