Home > Blockchain >  Flutter Intl library value.format to get . or , in thousands
Flutter Intl library value.format to get . or , in thousands

Time:11-28

I'm using the Intl library because I want to have thousands divided by the relative symbol (., as for example).

Then I want to have this: 12230 Modified to this: 12.230 (in my locale)

I would like to use Intl library because it has the locale automatism.

My code is:

final TextEditingController kcalEditingController =
              TextEditingController();
          kcalEditingController.addListener(() => setState(() {
                if (kcalEditingController.text.length > 3) {
                  NumberFormat numberFormat =
                      NumberFormat.decimalPattern(Platform.localeName);
                  kcalEditingController.text = numberFormat.format(int.parse(
                      kcalEditingController.text
                          .replaceAll(RegExp('[.,]'), '')));
                }
              }));

Anyway when I try to insert: 1254 all it's ok: result 1.254

By typing now eg. the number 5, the new result is: 51.254 (and not 12.545)

Also, after 4 digits, the 0 (zero) number stop responding...

As I can see, after typed the fourth number, the called the .format function, the cursor move to start (in my example before the number 1) and I'm non able, even manually or with mouse, to move it in last position (even in my example after the number 4).

CodePudding user response:

You should use a TextInputFormatter as in the following snippet:

TextFormField(
  controller: kcalEditingController ,
  decoration: InputDecoration(
    labelText: "My numeric field",
  ),
  inputFormatters: [NumberFormatter() ],
  keyboardType: TextInputType.numberWithOptions(decimal: true, signed: true),
),

import 'package:flutter/services.dart';
import 'package:intl/intl.dart';

class NumberFormatter extends TextInputFormatter {
  final NumberFormat numberFormat = NumberFormat.decimalPattern(Intl.getCurrentLocale());

  @override
  TextEditingValue formatEditUpdate(TextEditingValue oldValue, TextEditingValue newValue) {
    final text = newValue.text.length > 3 ? numberFormat.format(int.parse( newValue.text.replaceAll(RegExp('[.,]'), ''))) : newValue.text;
    return TextEditingValue(
      text: text,
      selection:  TextSelection.collapsed(offset: text.length)
    );
  }
}
  • Related