I want to use doubles in my code but Dart converts them to ints (or dynamic).
I have tried to cast them using 'as' or .toDouble() but they do not stay as doubles:
(in dartpad)
main() {
print ((1.0 as double).runtimeType);
print (1.0.toDouble().runtimeType);
}
(output)
int
int
I would have expected the output of these statements to be 'double'. If I change the value to 1.1 I get a double out.
Related
I really not satisfied with mql4 array function.In mql4 reference they cannot explain why need to use this function.
example why I need to use arrayinitialize function
When you declare some array, it may contain some garbage there. Most likely you will have default values, like 0 or NULL but garbage may stay there as well.
By use of 'ArrayInitialize()` function you can be sure that all the values in your array are the values you've put there.
string arr2str(const int &array[])//fn to print array, ugly, ends with ,|
{
string result="|";
for(int i=0;i<ArraySize(array);i++)
{
result+=(string)i+"="+(string)array[i]+", ";
}
return result+"|";
}
void OnTick()
{
int array[8];
printf("1: %d. %s",ArraySize(array),arr2str(array));
//receive: 1: 8. |0=0, 1=0, 2=0, 3=0, 4=1995110657, 5=146315416, 6=1, 7=85975080, |
int result=ArrayInitialize(array,7);
printf("2: %d %d. %s",result,ArraySize(array),arr2str(array));
//receive: 2: 8 8. |0=7, 1=7, 2=7, 3=7, 4=7, 5=7, 6=7, 7=7, |
ExpertRemove();//to stop the test
}
As you can see, first array output (1:) has some strange data. After initialization, no problem with it (2:) - all are sevens since I put 7 as second param in the function, it could be and most likely 0 instead of 7 in your codes.
I'm getting a Bluetooth Characteristic from a Bluetooth controller with flutter blue as a List. This characteristic contains weight measurement of a Bluetooth scale. Is there a function to convert this list of ints to a Double?
I tried to find some background on float representations by reading the IEEE 754 standard. There is the dart library typed_data but I am new to dart and have no experience with this lib.
Example:
I have this List: [191, 100, 29, 173] which is coming from a bluetooth controller as a IEEE754 representation for a float value.
Now i believe i have to convert each int to hex and concat these values: bf 64 1d ad
Next thing need to do is convert this to double, but i cannot find a function to convert hex to double. Only int.parse("0xbf641dad").
I guess your mean to convert the list of ints to a list of floats, not to a single float, right?
First, dart has no type called float. Instead it has type double. To convert it, you can use the map() function:
var listInt = [1, 2, 3];
var listDouble = list.map((i) => i.toDouble()).toList();
Had this same issue.
I think you mean how do you make the four bytes into a float32 ?
I needed to do the same thing.
you will want to do something like this:
first take the List value as a byte buffer, then take the byte data, then you can use the getFloat32 function.
ByteBuffer buffer = new Int8List.fromList(value_in).buffer;
ByteData byteData = new ByteData.view(buffer);
result = byteData.getFloat32(0);
Just be a little aware that the order of bytes from the Bluetooth may be back to front, as the convention varys.
Also you will need the typed_data library:
import 'dart:typed_data'; //for data formatting
I'm trying to go in the other direction now . . . for the obvious reason.
You may need this:
double parseHexString(String hexStr, bool littleEndian){
if(hexStr.length % 2 != 0){
return 0;
}
if(littleEndian == true){
List<int> bytes = hex.decode(hexStr).reversed.toList();
hexStr = hex.encode(bytes);
}
var byteConvert = ByteData(12);
byteConvert.setInt64(0, int.parse(hexStr,radix: 16));
return byteConvert.getFloat64(0);}
And demo :
double lat = parseHexString("0000004069665E40",true);
//lat = 121.60017395019531
If you already have:
int.parse("0xbf641dad")
I don't see why this wouldn't work:
int.parse("0xbf641dad").toDouble();
I used dart:typed_data for this:
import 'dart:typed_data';
List<int> intList = [191, 100, 29, 173];
double asFloat = ByteData.view(Uint8List.fromList(List.from(intList)).buffer).getFloat32(0, Endian.little);
Library reference: https://api.dart.dev/be/136883/dart-typed_data/dart-typed_data-library.html
Is it save to use cast to int instead of Math.floor to convert float / double values to integers?
var scale = 1.5;
int foo1 = (int)scale;
int foo2 = Math.floor(scale);
In this case both Case to Int and Math.floor will return integer value. If x=3.5 then both function will return 3 in output. Cast to int is a function to convert variable of any datatype to integer type, on the other hand Math.floor function will only floor the decimal number to integer not converting datatype. But result will be different in case of negative values because Cast to Int approaches to zero and Math.floor approaches to negative infinity. So in that perspective if you are working on real numbers (both positive and negative) then it is unsafe to use Cast to Int instead of Math.floor to get precise output.
As Vala code is translated into C, this is the same question as Cast to int vs floor
TL;DR: yes it is safe but the result of Math.floor and float/double casting are different when negative numbers are given.
Note that Math.floor is part of the GLib library and thus is not available in the POSIX profile.
weight is a field (Number in Firestore), set as 100.
int weight = json['weight'];
double weight = json['weight'];
int weight works fine, returns 100 as expected, but double weight crashes (Object.noSuchMethod exception) rather than returning 100.0, which is what I expected.
However, the following works:
num weight = json['weight'];
num.toDouble();
When parsing 100 from Firestore (which actually does not support a "number type", but converts it), it will by standard be parsed to an int.
Dart does not automatically "smartly" cast those types. In fact, you cannot cast an int to a double, which is the problem you are facing. If it were possible, your code would just work fine.
Parsing
Instead, you can parse it yourself:
double weight = json['weight'].toDouble();
Casting
What also works, is parsing the JSON to a num and then assigning it to a double, which will cast num to double.
double weight = json['weight'] as num;
This seems a bit odd at first and in fact the Dart Analysis tool (which is e.g. built in into the Dart plugin for VS Code and IntelliJ) will mark it as an "unnecessary cast", which it is not.
double a = 100; // this will not compile
double b = 100 as num; // this will compile, but is still marked as an "unnecessary cast"
double b = 100 as num compiles because num is the super class of double and Dart casts super to sub types even without explicit casts.
An explicit cast would be the follwing:
double a = 100 as double; // does not compile because int is not the super class of double
double b = (100 as num) as double; // compiles, you can also omit the double cast
Here is a nice read about "Types and casting in Dart".
Explanation
What happened to you is the following:
double weight;
weight = 100; // cannot compile because 100 is considered an int
// is the same as
weight = 100 as double; // which cannot work as I explained above
// Dart adds those casts automatically
You can do it in one line:
double weight = (json['weight'] as num).toDouble();
You can Parse the data Like given below:
Here document is a Map<String,dynamic>
double opening = double.tryParse(document['opening'].toString());
In Dart, int and double are separate types, both subtypes of num.
There is no automatic conversion between number types. If you write:
num n = 100;
double d = n;
you will get a run-time error. Dart's static type system allows unsafe down-casts, so the unsafe assignment of n to d (unsafe because not all num values are double values) is treated implicitly as:
num n = 100;
double d = n as double;
The as double checks that the value is actually a double (or null), and throws if it isn't. If that check succeeds, then it can safely assign the value to d since it is known to match the variable's type.
That's what's happening here. The actual value of json['weight'] (likely with static type Object or dynamic) is the int object with value 100. Assigning that to int works. Assigning it to num works. Assigning it to double throws.
The Dart JSON parser parses numbers as integers if they have no decimal or exponent parts (0.0 is a double, 0e0 is a double, 0 is an integer). That's very convenient in most cases, but occasionally annoying in cases like yours where you want a double, but the code creating the JSON didn't write it as a double.
In cases like that, you just have to write .toDouble() on the values when you extract them. That's a no-op on actual doubles.
As a side note, Dart compiled to JavaScript represents all numbers as the JavaScript Number type, which means that all numbers are doubles. In JS compiled code, all integers can be assigned to double without conversion. That will not work when the code is run on a non-JS implementation, like Flutter, Dart VM/server or ahead-of-time compilation for iOS, so don't depend on it, or your code will not be portable.
Simply convert int to double like this
int a = 10;
double b = a + 0.0;
is there any way to get absolute value from an integer?
for example
-8
to
8
I already tried to use UInt() assuming it will convert the Int to unsigned value but it didn't work.
The standard abs() function works great here:
let c = -8
print(abs(c))
// 8
With Swift 5, you may use one of the two following ways in order to convert an integer to its absolute value.
#1. Get absolute value of an Int from magnitude property
Int has a magnitude property. magnitude has the following declaration:
var magnitude: UInt { get }
For any numeric value x, x.magnitude is the absolute value of x.
The following code snippet shows how to use magnitude property in order to get the absolute value on an Int instance:
let value = -5
print(value.magnitude) // prints: 5
#2. Get absolute value of an Int from abs(_:) method
Swift has a global numeric function called abs(_:) method. abs(_:) has the following declaration:
func abs<T>(_ x: T) -> T where T : Comparable, T : SignedNumeric
Returns the absolute value of the given number.
The following code snippet shows how to use abs(_:) global function in order to get the absolute value on an Int instance:
let value = -5
print(abs(value)) // prints: 5
If you want to force a number to change or keep it positive.
Here is the way:
abs() for int
fabs() for double
fabsf() for float
If you want to get absolute value from a double or Int, use fabs func:
var c = -12.09
print(fabs(c)) // 12.09
c = -6
print(fabs(c)) // 6