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

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

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.

发布者:admin,转转请注明出处:http://www.yc00.com/questions/1742339578a4425348.html

相关推荐

发表回复

评论列表(0条)

  • 暂无评论

联系我们

400-800-8888

在线咨询: QQ交谈

邮件:admin@example.com

工作时间:周一至周五,9:30-18:30,节假日休息

关注微信