18

I want to round a double.

Double x = 5.56753;
x.toStringAsFixed(2);

When i put this, it gives 5.57000. But i want to get 5.57. How do i get it?

Sadisha
  • 364
  • 1
  • 2
  • 10

2 Answers2

38

there is num class contained function round():

Num

 double numberToRound = 5.56753;
    print(numberToRound.round()); 
    //prints 6

If you want decimals

double n = num.parse(numberToRound.toStringAsFixed(2));
  print(n);
  //prints 5.57

check comment sujestion

Chanaka Weerasinghe
  • 5,404
  • 2
  • 26
  • 39
  • 1
    At the time of posting this comment (i.e. 28 March 2021) this solution still violated the well-known "***numbers ending with 5***" rounding rule. See this answer => [ https://stackoverflow.com/a/66840734/3002719 ] for a DART solution that adheres to the number 5 round rule. – SilSur Mar 28 '21 at 11:30
9

For rounding doubles checkout: https://api.dartlang.org/stable/2.4.0/dart-core/double/round.html

Rounding won't work in your case because docs says:

  • Returns the integer closest to this.

So it will give 6 instead 5.57.

Your solution:

double x = 5.56753;
String roundedX = x.toStringAsFixed(2);
print(roundedX);
Mehmet Esen
  • 6,156
  • 3
  • 25
  • 44