Can I format a number before it is rendered in

后端 未结 4 1521
后悔当初
后悔当初 2021-01-07 20:24

I am rendering a node in Flutter app something like:

We have total ${_summary[\'bookCount\']} books. 

_summ

4条回答
  •  北海茫月
    2021-01-07 20:56

    There is a Dart package for formatting numbers, the Dart intl package. To use the package, add the following line to the Dart dependencies: pubspec.yaml file:

      intl: ">=0.14.0"
    

    Here's what my dependencies look like with the line:

    dependencies:
      flutter:
        sdk: flutter
    
      intl: ">=0.14.0"
    

    Click packages get in IntelliJ, or run flutter packages get from the command line.

    Make sure your class imports the intl package:

    import 'package:intl/intl.dart';

    In your code, you can use NumberFormat class to do the formatting:

      final formatter = new NumberFormat("#,###");
      new Text(formatter.format(1234)), // formatted number will be: 1,234
    

    Full stateful widget example:

    class NumberFormatExample extends StatefulWidget {
      @override
      _NumberFormatExampleState createState() => new _NumberFormatExampleState();
    }
    
    class _NumberFormatExampleState extends State {
      final formatter = new NumberFormat("#,###");
      int theValue = 1234;
    
      @override
      Widget build(BuildContext context) {
        return new Text(formatter.format(theValue));
      }
    }
    

提交回复
热议问题