salomepx
salomepx

Reputation: 83

How to round all numbers to 2 in the whole flutter project?

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.

Upvotes: 1

Views: 58

Answers (2)

Saad Bin Khalid
Saad Bin Khalid

Reputation: 11

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;

Upvotes: 1

Ravindra S. Patil
Ravindra S. Patil

Reputation: 14885

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),
      ),
    ),

Upvotes: 0

Related Questions