0

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 ?

Nautilus
  • 186
  • 3
  • 13

1 Answers1

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