How to convert a double to an int in Dart? - dart

The following produces the below error:
int calc_ranks(ranks)
{
double multiplier = .5;
return multiplier * ranks;
}
The return type double is not a int, as defined by the method calc_ranks. How do I round/cast to an int?

Round it using the round() method:
int calc_ranks(ranks) {
double multiplier = .5;
return (multiplier * ranks).round();
}

You can use any of the following.
double d = 20.5;
int i = d.toInt(); // i = 20
int i = d.round(); // i = 21
int i = d.ceil(); // i = 21
int i = d.floor(); // i = 20

You can simply use toInt() to convert a num to an int.
int calc_ranks(ranks)
{
double multiplier = .5;
return (multiplier * ranks).toInt();
}
Note that to do exactly the same thing you can use the Truncating division operator :
int calc_ranks(ranks) => ranks ~/ 2;

I see a lot of answers, but with less description. Hope my answer will add some value.
Lets initalize the variable, and see how it will change with different methods.
double x = 8.5;
toInt()
It truncates the decimal value.
int a = x.toInt();
print(a); // 8
truncate()
It also truncates the decimal value.
int b = x.truncate();
print(b); // 8
round()
It returns the closest integer. It uses half up rounding mode.
int c = x.round();
print(c); // 9
ceil()
It returns the closest integer greater than the value.
int c = x.ceil();
print(c); // 9
floor()
It returns the closest integer smaller than the value.
int c = x.floor();
print(c); // 8

I looked at the answers above and added some more answers to make it a little easier to understand.
double value = 10.5;
Using toInt()
void main(){
double value = 10.5;
var y = value.toInt();
print(y);
print(y.runtimeType);
}
Using round()
The round() method returns the closest integer to the double.
void main(){
double value = 9.6;
var b = value.round();
print(b);
print(b.runtimeType);
}
Using ceil()
The ceil() method returns the smallest integer that is equal or greater than the given double.
void main(){
double value = 9.5;
var d = value.ceil();
print(d);
print(d.runtimeType);
}
Using floor()
The floor() method returns the greatest integer not greater than the given double.
void main(){
double value = 10.9;
var j = value.floor();
print(j);
print(j.runtimeType);
}
Conclusion
We’ve gone through 4 different techniques to convert a double to an integer in Dart and Flutter. You can choose from the method that fits your use case to solve your problem. Flutter is awesome and provides a lot of amazing features.

To convert double to int just this:
division
double01 ~/ double02
PS: The operator x ~/ y is more efficient than (x / y).toInt().
Multiplication, addition and subtraction
(double01 * double02).toInt
(double01 + double02).toInt
(double01 - double02).toInt

Its easy,
(20.8).round()
For String,
double.tryParse(20.8).round()

from string to int ->
if you string in int format like '10'
then use ---->
int.parse(value)
but if string in double format like '10.6'
then use like this ---->
double.parse(value).toInt()
convert double to int
doubleValue.toInt()

Try this!
int calc_ranks(ranks)
{
double multiplier = .5;
return (multiplier * ranks).truncate();
}

class CurrencyUtils{
static int doubletoint(double doublee) {
double multiplier = .5;
return (multiplier * doublee).round();
}
}
----------------------
CustomText( CurrencyUtils.doubletoint(
double.parse(projPageListss[0].budget.toString())
).toString(),
fontSize: 20,
color: Colors.white,
font: Font.QuicksandSemiBold,
),

There's another alternative, you can first cast the double to 'num' datatype and then convert to int using toInt().
double multiplier = .5;
return ((multiplier * ranks) as num).toInt();
The num type is an inherited data type of the int and double types.
You can cast both int and double to num, then cast it again to whatever you want
(double -> use toDouble(), int -> use toInt())

Related

I built a function to calculate a price of an item each year. But my function won't read one of it's variable

I created a function to calculate the selling price of an item. Each year, the price of the item will decrease by 3/4 of its original price. The problem with my function is it doesn't want to read the year variable regardless of its value. My function always returns 60000000. Can someone please tell me what's wrong with it?
int add(double year, double price) {
int i = 0;
while (i < year) {
double final_price = price * 3 / 4;
i++;
return final_price.round();
}
}
void main(List<String> arguments) {
double x = 3;
double y = 80000000;
int result = add(x, y);
print(result);
}
int add(double year, double price) {
int i = 0;
double final_price=price; // change 1
while (i < year) {
final_price = final_price* 3 / 4; // change 2
i++;
}
return final_price.round(); // change 3
}
void main(List<String> arguments) {
double x = 3;
double y = 80000000;
int result = add(x, y);
print(result);
}
Here you go. Returning a value from inside the while loop will stop the function execution on the first traversal only.
Also you need to make final price equal to price because final_price's value is not being changed as price remains same and i increases.
what actually are you to trying to do ?
I fixed your code
int add(double year, double price) {
int i = 0;
double final_price = 0 ;
while (i < year) {
double f = price * 3 / 4;
i++;
final_price = f ;
}
return final_price.round();
}
void main() // you try to pass an arguments that never used I remove it
{
double x = 3;
double y = 800000;
int result = add(x, y);
print(result);
}

vala: quotient of two integers is always an integer. Why?

Newbie question:
void main () {
int A = 1;
int B = 2;
double C = A / B;
stdout.printf("C value is: %g\n", C);
}
This prints: "C value is: 0"
void main () {
int A = 1;
double B = 2;
double C = A / B;
stdout.printf("C value is: %g\n", C);
}
This prints: "C value is: 0.5"
I don't understand the reason why the result is not 0.5 in both cases.
The division operation is performed on two integers, so the result is an integer. The fact that you assign it to a double afterwards doesn't change that.
What you're doing in your question, with the implicit conversions made explicit, is
int A = 1;
int B = 2;
double C = (double) (A / B);
However, if you want to perform the division operation using doubles you have to explicitly cast at least one of the operands to double:
int A = 1;
int B = 2;
double C = ((double) A) / B;
For the rules concerning arithmetic operations, see the arithmetic expressions section of the Vala Manaual. The relevant bit:
If both operands are of integer types, then the result will be the quotient only of the calculation (equivalent to the precise answer rounded down to an integer value.) If either operand is of a floating point type, then the result will be as precise as possible within the boundaries of the result type (which is worked out from the basic arithmetic type rules.)

Objective C multiply 2 int*

This code show this error Invalid operands to binary expression ('int*' and 'int*')
int *a = 5;
int *b = 3;
int *c = a*b;
How I can multiply them, and Why is this a error?
you are initializing int* with an int value. To multiply values and write them to another pointer, you should call the value of a stored in an address with (*a)
here is the example code for what you want to do:
int *a = malloc(sizeof(int));
int *b = malloc(sizeof(int));
int *c = malloc(sizeof(int));
*a = 2;
*b = 3;
*c = (*a)*(*b);
printf("%d %d %d", *a,*b,*c);
free(a);
free(b);
free(c);
it prints 2 3 6 as expected.
this is the C (primitive type) Integer type so you cannot declare with pointer.
Please find the below code :
int a = 5;
int b = 3;
int c = (a*b);
Thanks
Please remove asterisk symbol because int is a primitive data type not an object. You can put asterisk symbol with objects not primitive data types.
Asterisk symbol is pointer symbol from the C language.
int a = 5;
int b = 3;
int c = a*b;

Storing functions in an array and applying them to an array of numbers

I've prototyped an algorithm for my iOS game in Python, and I need to rewrite in in ObjC. Basically, I have a board of 16 numbers, and I want to loop through every number three times and the four functions I'm using (add, subtract, multiply, exponentiate). 1+2+3, 2*3-4, 3^4-5, 9-4^3, etc., but without order of operations (first operation is always done first).
What I would like is an overview of how this might be implemented in Objective-C. Specifically, what is the equivalent of an array of functions in Objective-C? Is there an easy way to implement it with selectors? What's the best structure to use for loops with numbers? Array of NSIntegers, array of ints, NSArray/NSMutableArray of NSNumbers?
import random as rand
min = 0
max = 9
max_target = 20
maximum_to_calculate = 100
def multiply(x, y):
return x * y
def exponate(x, y):
return x ** y
def add(x, y):
return x + y
def subtract(x, y):
return x - y
function_array = [multiply, exponate, add, subtract]
board = [rand.randint(min, max) for i in xrange(0, 16)]
dict_of_frequencies = {}
for a in board:
for b in board:
for first_fun in function_array:
first_result = first_fun(a, b)
for c in board:
for second_fun in function_array:
final_result = second_fun(first_result, c)
if final_result not in dict_of_frequencies:
dict_of_frequencies[final_result] = 0
dict_of_frequencies[final_result] += 1
The most convenient way in Objective-C to construct an array of functions would be to use Blocks:
typedef NSInteger (^ArithmeticBlock)(NSInteger, NSInteger);
ArithmeticBlock add = ^NSInteger (NSInteger x, NSInteger y){
return x + y;
};
ArithmeticBlock sub = ^NSInteger (NSInteger x, NSInteger y){
return x - y;
};
NSArray * operations = #[add, sub];
Since there's no great way to perform arithmetic on NSNumbers, it would probably be best to create and store the board's values as primitives, such as NSIntegers, in a plain C array. You can box them up later easily enough, if necessary -- #(boardValue) gives you an NSNumber.
If you want to do it with straight C function pointers, something like this will do it:
#include <stdio.h>
#include <math.h>
long add(int a, int b) {
return a + b;
}
long subtract(int a, int b) {
return a - b;
}
long multiply(int a, int b) {
return a * b;
}
long exponate(int a, int b) {
return pow(a, b);
}
int main(void) {
long (*mfunc[4])(int, int) = {add, subtract, multiply, exponate};
char ops[4] = {'+', '-', '*', '^'};
for ( int i = 0; i < 4; ++i ) {
printf("5 %c 9 = %ld\n", ops[i], mfunc[i](5, 9));
}
return 0;
}
and gives the output:
paul#MacBook:~/Documents/src$ ./rndfnc
5 + 9 = 14
5 - 9 = -4
5 * 9 = 45
5 ^ 9 = 1953125
paul#MacBook:~/Documents/src$
Function pointer syntax can be slightly convoluted. long (*mfunc[4])(int, int) basically translates to defining a four-element array, called mfunc, of pointers to functions returning long and taking two arguments of type int.
Maddy is right. Anyway, I'll give it a try just for the fun of it.
This has never seen a compiler. So please forgive me all the typos and minor syntax errors in advance.
#include <stdlib.h>
...
const int MIN = 0;
const int MAX = 9;
const int MAX_TARGET = 20;
const int MAX_TO_CALCULATE = 100;
...
- (int) multiply:(int)x with:(int)y { return x * y; }
- (int) exponate:(int)x with:(int)y { return x ^ y; }
- (int) add:(int)x to:(int)y { return x + y; }
- (int) substract:(int)x by:(int)y { return x - y; }
// some method should start here, probably with
-(void) someMethod {
NSArray *functionArray = [NSArray arrayWithObjects: #selector(multiply::), #selector(exponate::), #selector(add::), #substract(multiply::), nil]; // there are other ways of generating an array of objects
NSMutableArray *board = [NSMutableArray arrayWithCapacity:16]; //Again, there are other ways available.
for (int i = 0; i < 16; i++) {
[board addObject:#(arc4random() % (MAX-MIN) + MIN)];
}
NSMutableDictionary dictOfFrequencies = [[NSMutableDictionary alloc] init];
for (NSNumber a in board)
for (NSNumber b in board)
for (SEL firstFun in functionArray) {
NSNumber firstResult = #([self performSelector:firstFun withObject:a withObject:b]);
NSNumber countedResults = [dictOfFrequencies objectForKey:firstResult];
if (countedResults) {
[dictOfFrequencies removeObjectForKey:firstResult];
countedResults = #(1 + [countedResults intValue]);
} else {
countedResults = #1; // BTW, using the # followed by a numeric expression creates an NSNumber object with the value 1.
}
[dictOfFrequencies setObject:countedResults forKey:firstResult];
}
}
Well, let me add some comments before others do. :-)
There is no need for objective c. You python code is iterative therefore you can implement it in plain C. Plain C is available where ever Objective C is.
If you really want to go for Objective-C here then you should forget your python code and implement the same logic (aiming for the same result) in Objective-C in an OOP style. My code really tries to translate your code as close as possible. Therefore my code is far far away from neither beeing good style nor maintainable nor proper OOP. Just keep that in mind before you think, ObjC was complicated compared to python :-)

How to get a random number from range in dart?

How does one get a random number within a range similar to c# Random.Next(int min, int max);
import 'dart:math';
final _random = new Random();
/**
* Generates a positive random integer uniformly distributed on the range
* from [min], inclusive, to [max], exclusive.
*/
int next(int min, int max) => min + _random.nextInt(max - min);
Range can be found with a simple formula as follows
Random rnd;
int min = 5;
int max = 10;
rnd = new Random();
r = min + rnd.nextInt(max - min);
print("$r is in the range of $min and $max");
You can achieve it via Random class object random.nextInt(max) . The nextInt() method requires a max limit. The random number starts from 0 and the max limit itself is exclusive.
import 'dart:math';
Random random = new Random();
int randomNumber = random.nextInt(100); // from 0 upto 99 included
If you want to add the min limit, add the min limit to the result
int randomNumber = random.nextInt(90) + 10; // from 10 upto 99 included
This is really late, but this for anyone who still has the question.
The easiest way to get a random number between a min and a max is the following :
import 'dart:math';
int max = 10;
int randomNumber = Random().nextInt(max) + 1;
The math module in dart has a function called nextInt. This will return an integer from 0 (including 0 ) to max - 1 ( exluding max ). I want a number 1 to 10, hence I add 1 to the nextInt result.
Generates a random integer uniformly distributed in the
range from [min] to [max], both inclusive.
int nextInt(int min, int max) => min + _random.nextInt((max + 1) - min);
It can be achieved exactly as you intended by creating extension on int to get random int value. For example:
import 'dart:math';
import 'package:flutter/foundation.dart';
extension RandomInt on int {
static int generate({int min = 0, #required int max}) {
final _random = Random();
return min + _random.nextInt(max - min);
}
}
And you can use this in your code like so:
List<int> rands = [];
for (int j = 0; j < 19; j++) {
rands.add(RandomInt.generate(max: 50));
}
Note that static extension methods can't be called on type itself (e.g. int.generate(min:10, max:20)), but instead you have to use extension name itself, in this example RandomInt. For detailed discussion, read here.
import 'dart:math';
Random rnd = new Random();
// Define min and max value
int min = 1, max = 10;
//Getting range
int num = min + rnd.nextInt(max - min);
print("$num is in the range of $min and $max");
To generate a random double within a range, multiply a random int with a random double.
import 'dart:math';
Random random = new Random();
int min = 1, max = 10;
double num = (min + random.nextInt(max - min)) * random.nextDouble();
To Generate a random positive integer between a given range:
final _random = new Random();
// from MIN(inclusive), to MAX(exclusive).
int randomBetween(int min, int max) => min + _random.nextInt(max - min);
// from MIN(inclusive), to MAX(inclusive).
int randomBetween(int min, int max) => min + _random.nextInt((max+1) - min);
// from MIN(exclusive), to MAX(exclusive).
int randomBetween(int min, int max) => (min+1) + _random.nextInt(max - (min+1));
When I was making a Tetris game, I had to rotate the x-axis. For this, I wrote the following codes.
I hope it will be useful for you too:
Random rnd = Random();
int min = 0;
int max = 23;
class Block {
int x = min + rnd.nextInt(max - min);
}
A simpler way of doing this is to use the nextInt method within Random:
// Random 50 to 100:
int min = 50;
int max = 100;
int selection = min + (Random(1).nextInt(max-min));
https://api.dartlang.org/stable/2.0.0/dart-math/Random-class.html

Resources