1

Below is the code where the error occurs.

I want to convert [NumberFormat][1] form to double. What should I do?

I want to display it on the screen with the currency symbol, and get the result as a double .

Sample source:

import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:intl/intl.dart';

class ProductEditor extends StatefulWidget {
  const ProductEditor({Key? key}) : super(key: key);

  @override
  _ProductEditorState createState() => _ProductEditorState();
}

class _ProductEditorState extends State<ProductEditor> {
  final NumberFormat euNumFormat =
      NumberFormat.currency(locale: 'eu_EU', symbol: '€');
  TextEditingController _ctrPrice = TextEditingController();

  double _price = 25000.00;

  @override
  void initState() {
    super.initState();

    _ctrPrice.text = euNumFormat.format(_price); // 
  }

  @override
  Widget build(BuildContext context) {
    return Container(
      width: 500,
      height: 300,
      child: TextField(
        controller: _ctrPrice,
        onSubmitted: (String price) {
          setState(() {
            final double value = double.tryParse(_ctrPrice.text
                    .substring(0, _ctrPrice.text.length - 2)
                    .replaceAll(',', '')) ??
                0.0;
            print('price:${_ctrPrice.value.toString()}    ${value}');

            final formattedPrice = euNumFormat.format(value);

            _ctrPrice.value = TextEditingValue(
              text: formattedPrice,
              selection: TextSelection.collapsed(offset: formattedPrice.length),
            );
          });
        },
      ),
    );
  }
}
Patrick SINT
  • 454
  • 1
  • 4
  • 13
  • I would suggest to hold double value in `TextEditingController`'s `_ctrPrice.value` field, and formatted one to hold on `_ctrPrice.text` field. And when submitting, just take the `value` from controller. – Kęstutis Ramulionis Jan 25 '22 at 08:15

1 Answers1

0

You can create a substring by removing symbol and , from there, then parse it.

final double retailPrice = double.tryParse(
        _ctrPrice.substring(0, _ctrPrice.length - 2).replaceAll(",", ''),
      ) ??
      0.0;

This solution only work on specific number format('eu_EU').

Md. Yeasin Sheikh
  • 54,221
  • 7
  • 29
  • 56