I have the following number in decimal
double x = 2.888888888888889;
, but I have not been able to obtain 2.9
as a result.How is it done? is there a way to do this? that approaches 1 decimal more like the rules of mathematics? if it is 3.5 that the result is 3.6 ?
Asked
Active
Viewed 341 times
0

Nautilus
- 186
- 3
- 13
-
1`double.round()` In mathematics, if it's 3.5 then it's 4.0 when approximated at least that's what i was taught. Check [round](https://api.flutter.dev/flutter/dart-core/double/round.html) – Frank nike Mar 17 '22 at 21:21
-
@Franknike Use round() but it doesn't work for me, must be more exact result. – Nautilus Mar 17 '22 at 21:26
-
1The answer below will solve it – Frank nike Mar 17 '22 at 21:33
1 Answers
2
There are at least two ways, check this out:
void main() {
double number = 2.888888888;
double roundedByString = double.parse(number.toStringAsFixed(1));
print(roundedByString); // prints 2.9
double roundedByTenthInt = (number * 10).round() / 10;
print(roundedByTenthInt); // prints 2.9
}

tmaihoff
- 2,867
- 1
- 18
- 40
-
You are the answer that I was looking for so much, you have saved me, thank you !! – Nautilus Mar 17 '22 at 21:38
-
Be aware that what this will do is to set `roundedByString` and `roundedByTenthInt` to the `double` value *nearest* to 2.9 (which will be 2.899999999999999911182158029987476766109466552734375). You inherently cannot exactly round most *binary* floating-point numbers to a *decimal* precision. Also see https://stackoverflow.com/a/68980598/ – jamesdlin Mar 17 '22 at 22:08