Dart/Flutter – How to round a Number to N decimal places

In this short article, we are going to learn how to round a number to n decimal places in Dart/Flutter. Or in other words, we format a number to a decimal number with N digits after decimal point.

Let’s go directly into the demo because there are no special things to explain   🧑‍🎄 🧑‍🎄 🧑‍🎄

void main() {
  double number = double.parse(1.2345.toStringAsFixed(2));
  print(number); // 1.23 

  number = double.parse(1.2356.toStringAsFixed(2));
  print(number); // 1.24

  number = double.parse((-1.2345).toStringAsFixed(2));
  print(number); // -1.23

  number = double.parse((-1.2356).toStringAsFixed(2));
  print(number); // -1.24
}

Tagged : / / / /
Subscribe
Notify of
guest

1 Comment
Newest
Oldest Most Voted
Inline Feedbacks
View all comments
Bobby
Bobby
3 years ago

Thanks!

1
0
Would love your thoughts, please comment.x
()
x