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?
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.
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.
To round a double number to two decimal places in Dart and Flutter, you can use the toStringAsFixed() method.
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:
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);
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With