Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to round a number in dart? [duplicate]

Tags:

dart

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?

like image 834
Sadisha Avatar asked Jul 12 '19 07:07

Sadisha


People also ask

How do you round a double in darts?

Dart round double to N decimal places – Multiply the number by 10^N (using pow() function), then round the result to integer and divide it by 10^N . For example, we want to round double to 2 decimal places. Assume that the number is 12.3412 : Step 1: 12.3412 * 10^2 = 1234.12.

Can you double round a number?

Double rounding is often harmless, giving the same result as rounding once, directly from n0 digits to n2 digits. However, sometimes a doubly rounded result will be incorrect, in which case we say that a double rounding error has occurred. For example, consider the 6-digit decimal number 7.23496.

How do you show 2 decimal places in darts?

To round a double number to two decimal places in Dart and Flutter, you can use the toStringAsFixed() method.


2 Answers

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);
like image 95
Esen Mehmet Avatar answered Oct 11 '22 19:10

Esen Mehmet


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

like image 44
Chanaka Weerasinghe Avatar answered Oct 11 '22 19:10

Chanaka Weerasinghe