How to round the double value upto two decimal points in dart?

6,197

You can use the String toStringAsFixed(int fractionDigits)

  • Returns a decimal-point string-representation of this.

  • Converts this to a double before computing the string representation.

  • If the absolute value of this is greater or equal to 10^21 then this methods returns an exponential representation computed by this.toStringAsExponential(). Otherwise the result is the closest string representation with exactly fractionDigits digits after the decimal point. If fractionDigits equals 0 then the decimal point is omitted.

  • The parameter fractionDigits must be an integer satisfying: 0 <= fractionDigits <= 20.

Examples:

1.toStringAsFixed(3);  // 1.000
(4321.12345678).toStringAsFixed(3);  // 4321.123
(4321.12345678).toStringAsFixed(5);  // 4321.12346
123456789012345678901.toStringAsFixed(3);  // 123456789012345683968.000
1000000000000000000000.toStringAsFixed(3); // 1e+21
5.25.toStringAsFixed(0); // 5

For more information check out official documentation.

Share:
6,197
Umair
Author by

Umair

Updated on December 15, 2022

Comments

  • Umair
    Umair over 1 year

    I have made this method that was called to perform functionality and do calculation but return number in double format for some calculations upto more than 10 decimal points. How can i make this code to show only upto 2 or 3 decimal points?

    getProductPrice(int productID) {
        var cart = cartlist.firstWhere((cart) => cart.product.id == productID,
            orElse: () => null);
        if (cart != null) {
          var price= (cart.count)*(cart.product.price);
          return price;
          notifyListeners();
        } else {
          return 0.0;
        }
      }