Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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;
    }
  }
like image 854
Umair Avatar asked Nov 06 '19 08:11

Umair


People also ask

How do you set precision in darts?

In Dart, If you have a double and you need to set a certain precision to the number while rounding the value at the same time, you can use the following method. String toStringAsFixed(int fractionDigits); The method has one parameter fractionDigits which is used to set how many decimal points in the output.


1 Answers

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.

like image 59
ibhavikmakwana Avatar answered Oct 01 '22 02:10

ibhavikmakwana