Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Easily check if a number is in a given Range in Dart?

Tags:

dart

Is there an operator or function in Dart to easily verify if a number is in a range? Something like Kotlin in operator:

https://kotlinlang.org/docs/reference/ranges.html

if (i in 1..10) { // equivalent of 1 <= i && i <= 10
    println(i)
}
like image 629
alexpfx Avatar asked Dec 15 '18 21:12

alexpfx


People also ask

How do you check if a number is an integer in Dart?

Dart numbers (the type num ) are either integers (type int ) or doubles (type double ). It is easy to check if a number is an int , just do value is int .

How do you check if a number is a value in flutter?

To check whether a string is a numeric string, you can use the double. tryParse() method. If the return equals null then the input is not a numeric string, otherwise, it is.

How do you use a Dart float?

The Double data type in Dart represents a 64-bit (double-precision) floating-point number. For example, the value "10.10". The keyword double is used to represent floating point literals.

What is the difference between NUM and int in Dart?

Dart numbers can be classified as: The int data type is used to represent whole numbers. The double data type is used to represent 64-bit floating-point numbers. The num type is an inherited data type of the int and double types.


3 Answers

Quite simply, no. Just use 1 <= i && i <= 10.

like image 99
Randal Schwartz Avatar answered Oct 17 '22 12:10

Randal Schwartz


Since the inclusion of extension functions, this answer could be changed slightly if you are okay with doing the checks non-inline.

To my knowledge, there is no built in functions for this, but you could easily create your own extension on num to simulate this.

Something like this would simulate a range verification:

void main() {
  final i = 2;
  if (i.isBetween(1, 10)) {
    print('Between');
  } else {
    print('Not between');
  }
}

extension Range on num {
  bool isBetween(num from, num to) {
    return from < this && this < to;
  }
}

This method in particular is exclusive both from and to, but with minor tweaking and better naming you could easily create extension functions for all of the Kotlin range checks.

like image 19
lohnn Avatar answered Oct 17 '22 11:10

lohnn


I find using clamp more readable. So, to check if i is between 1 and 10, clamp it to the range and compare to itself.

if (i.clamp(1,10) == i) {
    print(i);
}

Documentation for clamp

like image 8
Karthik Rajendran Avatar answered Oct 17 '22 12:10

Karthik Rajendran