skip to Main Content

I welcome everyone. Can you please tell me how to compare 2 List, rounding the values, for example, to two decimal places?

We have

var list1 = [3425,5559394484, 2351,4392210480, -2384,4831199322];
var list2 = [3425,5559394472, 2351,4392210480, -2384,4831199122];

You need to compare the values of the lists, rounding them up to 2 decimal places. the result should

be
print(ListEquality().equals(list1, list2)) // true

What is the best way to implement comparison? Thanks to everyone who will respond.

3

Answers


  1. Besides using answer below comment, you can do like this:

    bool checkEquals(List<double> list1, List<double> list2) {
      if (list1.length != list2.length) {
        return false;
      }
    
      for (int i = 0; i < list1.length; i++) {
        if (_roundToTwoDecimals(list1[i]) != _roundToTwoDecimals(list2[i])) {
          return false;
        }
      }
    
      return true;
    }
    
    double _roundToTwoDecimals(double value) {
      return double.parse(value.toStringAsFixed(2));
    }
    
    
    void main() {
      var list1 = [3425.5559394484, 2351.4392210480, -2384.4831199322];
      var list2 = [3425.5559394472, 2351.4392210480, -2384.4831199122];
    
      print(checkEquals(list1, list2));  // Output: true
    }
    
    Login or Signup to reply.
  2. You can try the below soln

    I make method for length & equality which return true or false

    void main() {
      var list1 = [3425.5559394484, 2351.4392210480, -2384.4831199322];
      var list2 = [3425.5559394472, 2351.4392210480, -2384.4831199122];
    
      print(checkEqAndLength(list1, list2));  // Output: true
    }
    
    
    
    
    bool checkEqAndLength(List<double> l1, List<double> l2) {
      if (l1.length != l2.length) {
        return false;
      }
    
      for (int i = 0; i < l1.length; i++) { 
        if(double.parse(l1[i].toStringAsFixed(2)) != double.parse(l2[i].toStringAsFixed(2))){
          return false;
        }
      }
      return true;
    }
    
    Login or Signup to reply.
  3. import 'package:collection/collection.dart';
    
    void main() {
      var list1 = [3425.5559394484, 2351.4392210480, -2384.4831199322];
      var list2 = [3425.5559394472, 2351.4392210480, -2384.4831199122];
    
      final doubleEquality = EqualityBy<double, double>(_roundDouble);
      print(ListEquality(doubleEquality).equals(list1, list2));
    }
    
    double _roundDouble(double value) {
      return (value * 100).roundToDouble() / 100;
    }
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search