How to Round numbers at 0.6, 1,6, 2,6,…?

2020-05-09 23:07发布

问题:

I want this to be true for all numbers. I don't want to type this for all numbers of course.

 if (overs == 0.6) {
  overs = 1.0;
}

I want that if for example 1.6, is reached, it should be converted to 2. I want this to be true for all numbers.

Further Clarification: I don't want it to round at For eg 0.5, i want it to round at 0.6

回答1:

One Liner

double roundAt6(double n) => (n - n.floor()) > 0.5 ? n.ceil() : n;

Detailed

void main() {
  final double overs = 5.6;
  print('result: ${roundAt6(overs)}');
}

double roundAt6(double n) {
  final double decimalPart = n - n.floor();
  print('decimal part: $decimalPart');
  final bool didExceed = decimalPart > 0.5;
  print('didExceed: $didExceed');
  return didExceed ? n.ceil() : n;
}


回答2:

Maybe ceil()

Returns the least integer no smaller than this.

Example

overs = overs.ceil()



回答3:

Use round() method.

Returns the integer closest to this.

Example

overs = overs.round()


回答4:

Insights porvided by @Amsakanna helped me solve the problem. I am posting the exact solution here:

 if ((overs - overs.floor()) > 0.55) 
{
overs = overs - (overs - overs.floor()) + 1; 
}


标签: dart