skip to Main Content

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.

2

Answers


  1. 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. 😁

    Login or Signup to reply.
  2. The error occurs because the string you are trying to parse ($4,249,000.00) contains characters like the dollar sign ($) and commas (,) that are not valid in a numeric format. To convert this string to a double, you need to preprocess it to remove any non-numeric characters except the decimal point.

    Solution:

    String salePriceText = salePriceController.text;
    String cleanedText = salePriceText.replaceAll(RegExp(r'[^0-9.]'), '');
    double salePrice = double.parse(cleanedText);
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search