1

下面是发生错误的代码。

我想将 [NumberFormat][1] 表单转换为双精度。我应该怎么办?

我想用货币符号在屏幕上显示它,并将结果作为 double 。

样本来源:

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),
            );
          });
        },
      ),
    );
  }
}
4

1 回答 1

0

symbol您可以通过从那里删除和创建子字符串,,然后对其进行解析。

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

此解决方案仅适用于特定的数字格式('eu_EU')。

于 2022-01-25T09:33:07.740 回答