This question already has an answer here:
why abs() function in dart return negative number when not wrapped in parenthesis?
(1 answer)
Closed 12 months ago.
void main() {
var x = -5.abs();
print(x);
}
Will be -5.
But:
void main() {
var x = -5;
print(x.abs());
}
Will be 5.
-5 is an object, and the result of -5.abs() will be connected to x. But we still see -5. Could you please correct me where I wrong?
I think what Dart does is:
var x = (-1)*5.abs();
You can use var x = (-5).abs(); to get 5
void main() {
var x = -5.abs();
print(x);
}
is almost certainly parsed as
void main() {
var x = -(5.abs());
print(x);
}
and since 5 is already positive, it comes back unchanged. And then you negate that result.
Related
This question already has answers here:
Is floating point math broken?
(31 answers)
How do you round a double in Dart to a given degree of precision AFTER the decimal point?
(28 answers)
Closed 12 months ago.
Dart calculations are off. We're running into rounding issues (financial app)
Here an example
Dartpad output
Hours : 7.5
Rate : 19.61
Val (Hours * Rate) : 147.075
Val * 100 (should be 14707.5) : 14707.499999999998
Round Val (now rounds down) : 14707
Val / 100 : 147.07 (should have been 147.08)
This is causing rounding errors displaying values to 2 decimal places.
Is there a way to accomplish this accurately in dart?
This is a floating point precision thing, nothing really to do with the language itself. There are many ways around this problem. See mine below.
void main() {
var vHours = 7.5;
print('Hours : $vHours');
var vRate = 19.61;
print('Rate : $vRate');
var vValue = vHours * vRate;
print('Val (Hours * Rate) : $vValue');
print('');
var vMul = (vValue * 100);
var vMulString = vMul.toStringAsFixed(2);
var vMulParsed = num.parse(vMulString);
print('Val * 100 (should be 14707.5) : $vMulParsed');
var vMulRounded = vMulParsed.round();
print('Round Val (now rounds down) : $vMulRounded');
var vDiv = vMulRounded / 100;
print('Val / 100 : $vDiv (should have been 147.08)');
}
//Works on Dartpad
main() {
var pi = 3.14; //3.14159265359
var numbers = 0;
dynamic result = 1.2;
while (result.runtimeType == double) {
numbers++;
result = numbers * pi;
}
print('$result / $numbers = $pi');
}
//Works on local
main() {
var pi = 3.14; //3.14159265359
var numbers = 0;
dynamic result = 1.2;
while ((result - result.truncate()) != 0) {
numbers++;
result = numbers * pi;
}
print('${result.truncate()} / $numbers = $pi');
}
The problem is whenever you initialize a double variable, the dartpad can convert it to an integer when it becomes an integer but the local compiler doesn't do that.
Could this be caused by js? Because as far as I know dartpad compiles with js.
What you are observing is Dart trying to hide the limitation of JavaScript where numbers is always represented as double objects (so no int). Since DartPad is compiling your code to JavaScript and then executes it in your browser, you will get this behavior.
For more details I recommend looking at this StackOverflow question where I have made a detailed example that shows how numbers in Dart behave when running your program natively and as JavaScript: Why dart infers the variable type as a int when I explicitly say the type is double?
So guys how do we generate a random number between a range but that shouldnt contain a particular no. in that range in dart?
If you want to print random numbers from 0 to 999 except say, the number 100.
Then the following code fragment will be sufficient.
import 'dart:math';
void main() {
var n = 100;
do {
r = rng.nextInt(1000);
} while (r == n);
print(r);
}
Depends on requirements for time, and distribution of result, say you wish to preserve even distribution and want to avoid calling a new random number, and are using the range 0-2000 and filling in 100
import 'dart:math';
void main() {
var n = 100;
do {
r = rng.nextInt(2000);
}
if (r >= n){
r++
}
print(r);
}
Let me show u an example;
// created my method to get random numbers and use wherever I want
// used math library to create numbers randomly and equaled to numbers.
// now we have to check if it will contains 0 so we will call method again to create new random numbers list which one no including 0.
import 'dart:math';
int void randomNumbers()
{
int numbers=Random().NextInt(10);
if(numbers!=0)
{
return numbers;
}
else
{
int newNumbers= randomNumbers();
return newNumbers,
}
}
so u can call that method created below in anytime to anywhere.
Here is an example: We set a FlatButton and when pressed, the var "leftdicenumber" receives a random number betxeen 1 and 6:
FlatButton(
onPressed: () {
leftdicenumber = Random().nextInt(6) + 1;
},);
func averageOf(numbers: Int...) -> Float {
var sum = 0
var i = 1
for number in numbers {
sum += number
i++
}
return Float(sum)/Float(i)
}
averageOf(1,2,3,4,4)
return value
2.33333325386047
Im new to Swift and run this code in the playground. The return value is not right, but I cannot find where is wrong, since the sum is 14 and the i is 5.
Start with i=0 instead of one. Since you're incrementing i after each number, i is ending up as 6 in your example instead of 5.
I don't see any way to round a number in Dart?
import 'dart:math';
main() {
print(Math.round(5.5)); // Error!
}
http://api.dartlang.org/docs/bleeding_edge/dart_math.html
Yes, there is a way to do this. The num class has a method called round():
var foo = 6.28;
print(foo.round()); // 6
var bar = -6.5;
print(bar.round()); // -7
In Dart, everything is an object. So, when you declare a num, for example, you can round it through the round method from the num class, the following code would print 6
num foo = 5.6;
print(foo.round()); //prints 6
In your case, you could do:
main() {
print((5.5).round());
}
This equation will help you
int a = 500;
int b = 250;
int c;
c = a ~/ b;
UPDATE March 2021:
The round() method has moved to https://api.dart.dev/stable/2.12.2/dart-core/num/round.html. All the above links are wrong.
Maybe this can help in specific situations, floor() will round towards the negative infinite
https://api.dart.dev/stable/2.13.4/dart-core/num/floor.html
void main() {
var foo = 3.9;
var bar = foo.floor();
print(bar);//prints 3
}