Home > Software design >  How to round integer number using precision in flutter
How to round integer number using precision in flutter

Time:04-07

I am trying to make the Y axis intervals of linechart dynamic in flutter. Here the MaxVal will get the maximum value of the Y axis.

int interval = (maxVal/6).toInt();
int length = interval.toString().length.toInt();

So here I have divided the maxVal with 6 so I will get the interval and I will find out the length. Next I need to round the interval according to the length. But I couldn't see any option to add precision for in flutter.

The Expected Output

If maxVal = 10000 then interval will 1666 then length will 4. Then I expected rounded value will be 2000

CodePudding user response:

I'm assuming that you're asking to round a (non-negative) integer to its most significant base-10 digit. A general way to round non-negative integers is to add half of the unit you want to round to and to then truncate. For example, if you want to round a non-negative integer to the nearest 1000, you can add 1000/2 = 500, and then discard the hundreds, tens, and ones digits. An easy way to discard those digits is to perform an integer division by 1000 and then to multiply by 1000 again.

The trickiest part is determining what unit you want to round to since that's variable. If you want the most significant base-10 digit, you will need to determine the number of digits. In theory you can compute that with logarithms, but it's usually risky to depend on exact results with floating-point arithmetic, you'd have to deal with 0 as a special case, and it's harder to be confident of correctness. It's simpler and less error-prone to just find the length of the number's string representation. Once we find the number of digits, we can determine which unit to round to computing a corresponding power of 10.

import 'dart:math';

int roundToMostSignificantDigit(int n) {
  var numDigits = n.toString().length;
  var magnitude = pow(10, numDigits - 1) as int;
  return ((n   (magnitude ~/ 2)) ~/ magnitude) * magnitude;
}

void main() {
  var inputs = [
    0,
    1,
    5,
    9,
    10,
    11,
    16,
    19,
    20,
    21,
    49,
    50,
    51,
    99,
    100,
    469,
    833,
    1666,
  ];
  for (var n in inputs) {
    var rounded = roundToMostSignificantDigit(n);
    print('$n => $rounded');
  }
}

which prints:

0 => 0
1 => 1
5 => 5
9 => 9
10 => 10
11 => 10
16 => 20
19 => 20
20 => 20
21 => 20
49 => 50
50 => 50
51 => 50
99 => 100
100 => 100
469 => 500
833 => 800
1666 => 2000
  • Related