skip to Main Content

I am working on a flutter app with banking numbers, and therefore only needs two decimal numbers. Is there a way to round every number automatically in my whole project at once ?

The idea is to not use amount.toStringAsFixed(2) all the time.

2

Answers


  1. Yes you can create one common method for this like below

    Access amountFix every where in your whole code like below:

    void main() {
      print(CommonMethod.amountFix(125.599));
    }
    

    Your common method declare below:

    class CommonMethod {
      static amountFix(double amount) {
        return amount.toStringAsFixed(2);
      }
    }
    

    you can access in widget as well like below:

       Center(
          child: Text(
            CommonMethod.amountFix(125.599),
          ),
        ),
    
    Login or Signup to reply.
  2. You can make use of dart extension methods.

    Define the logic for formatting numbers in an extension.

    extension PriceStringExt on num {
      String get priceStr {
        return toStringAsFixed(2);
      }
    }
    

    Use it anywhere in your project.

    int price = 12;
    price.priceStr;
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search