Calculate difference between two sets of dates and divide the results in Flutter
You are using integer division ~/ instead of float division /
void main() {
var date1calc = 140;
var date2calc = 270;
print(date1calc / date2calc);
}
prints 0.5185185185185185
cc976a
Updated on December 27, 2022Comments
-
cc976a over 1 year
I have four dates (date1, date2, date3 and date4).
I have a script that works out the number of days between date1 and date2 ('date1calc') - then works out the number of days between date3 and date4 ('date2calc').
What I now want to do is date1calc divided by date2calc to give me a value. We'll call this 'dateValue'. Although I get the correct values for date1calc and date2calc it displays dateValue as '0'.
Here is the code:
var date1calc = singleDate.difference(dateNow).inDays; var date2calc = singleDate.difference(startSingleDate).inDays; var dateValue = date1calc ~/ date2calc;
When I print out the values of all three, it shows:
date1calc = 140 date2calc = 270 dateValue = 0
Why is dateValue showing as '0' instead of '0.5185'?
Thanks in advance
**** Update ****
Thanks to edbond - that fixed the issue I had, and the console correctly displayed dateValue as 0.5185xxxxxxxx
This though left me another issue which was ''double' is not a subtype of type 'int'
To fix this - and in case anyone else stumbles upon this for an answer - I found another solution to turn the double in to an int:
double x = dateValue; int a = x.toInt(); var dateValue2 = a;
By then calling 'dateValue2', instead of 'dateValue in to the rest of my code, it worked like a charm!
I can't say it's the 'best' way of doing this, but it worked for me.
-
cc976a over 3 yearsThat fixed the console output - thanks!! .... it has triggered a separate error though in the Console which shows " type 'double' is not a subtype of type 'int' " .....I'm trying to investigate this further