Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What's the logic of clamp function in dart?

Tags:

flutter

dart

Numeric classes like int, double, num has clamp function. I try it and have some results.. I guess it has a logic like

a = math.max(-1, math.min(1, a));

but when I print this code I have the strange result

print(-100.43.clamp(-400.2, 64.2)); // -64.2

What's the algorithm of dart's clamp function?

like image 226
Daniyar Avatar asked Jul 10 '19 12:07

Daniyar


1 Answers

The Clamp function of the dart is actually taking the number not the sign of the number

print(-100.43.clamp(-400.2, 64.2)); gives ->  -64.2

because it takes ( -100 ) as ( 100 ) only and if we do =>

100.clamp(-400,64.2) it gives -> 64.2

and after negative comes and finally becomes: -64.2 to check this you can do this :

print((-100.43 + 0).clamp(-400.2, 64.2))); // it will give: -100.43

or

double value = -100;
print(value.clamp(-400.2, 64.2)));

so you can use this to prevent this behavior.

like image 161
akash maurya Avatar answered Nov 08 '22 11:11

akash maurya