I have the following section of code in an app that I am writing:
...
String[] Columns = Regex.Split(CurrentLine, Delimeter);
Nullable<Double> AltFrom;
...
if (AltFrom == null)
{
Double.TryParse(Columns[LatIndex].Trim(), out AltFrom);
}
...
The line in the if clause will not compile and shows the error: cannot convert from 'out double?' to 'out double'
if I don't make AltFrom a Nullable type and rather explicitly state it as a Double, everything is happy.
Surely this is valid code. Is this just a bug in c# or am I doing something wrong?
No the out parameter really needs to be a double, not a Nullable<double>.
double? altFrom = null;
double temp = 0;
if (double.TryParse( Columns[LatIndex].Trim(), out temp))
{
altFrom = temp;
}
First, you can not implicitly convert a double? to a double. The reason is because what would be the value of the double if the double? represented the null value (i.e., value.HasValue is false)? That is, converting from a double? to a double results in a loss of information (it is a narrowing conversion). Implicit narrowing conversions are generally frowned upon in the framework.
But actually, the problem that you are seeing here is something different. When you have a method that accepts an out parameter of type T, you must pass in a variable of type T; there can not be any type variation in this case as there is with non-ref and non-out parameters.
To get around your problem, use the following:
if (AltFrom == null) {
double value;
Double.TryParse(Columns[LatIndex].Trim(), out value);
AltFrom = value;
}
Related
Ive tried to use double.parse, double.tryparse as well as trying to convert it to int but it keeps giving the error 'type 'int' is not a subtype of type 'String'', ive searched a few sites but all the solutions show to use parse.
final locData = Map<String, dynamic>.from(local);
var dubLat = locData['lat'];
var lat = double.tryParse(dubLat);
ive tried changing var to double nit still give the same error.
The .tryParse takes a string or even the parse method for this instance takes a string. But your data is actually integers therefore the error type int is not a subtype of type string. You should consider either storing them as ints or using the .toString method before parsing them.
var dubLat = locData['lat']; // Here dublat is not actually a string but integer. Your map has dynamic as a second parameter it can take all data types and this particular datatype is int not string which .parse expects.
var lat = double.tryParse(dubLat.toString());
You are facing this error because you are trying to pass int but double.tryParse need string value that's why getting this error 'type 'int' is not a subtype of type 'String'
I solved by this 'double.tryParse(dubLat.toString());'
final locData = Map<String, dynamic>.from(local);
var dubLat = locData['lat'];
var lat = double.tryParse(dubLat.toString());
Very simple issue. I have the useless class:
class Useless{
double field;
Useless(this.field);
}
I then commit the mortal sin and call new Useless(0);
In checked mode (which is how I run my tests) that blows up, because 'int' is not a subtype of type 'double'.
Now, it works if I use new Useless(0.0) , but honestly I spend a lot of time correcting my tests putting .0s everywhere and I feel pretty dumb doing that.
As a temporary measure I rewrote the constructor as:
class Useless{
double field;
Useless(num input){
field = input.toDouble();
}
}
But that's ugly and I am afraid slow if called often. Is there a better way to do this?
Simply toDouble()
Example:
int intVar = 5;
double doubleVar = intVar.toDouble();
Thanks to #jamesdlin who actually gave this answer in a comment to my previous answer...
In Dart 2.1, integer literals may be directly used where double is expected. (See https://github.com/dart-lang/sdk/issues/34355.)
Note that this is syntactic sugar and applies only to literals. int variables still won't be automatically promoted to double, so code like:
double reciprocal(double d) => 1 / d;
int x = 42;
reciprocal(x);
would fail, and you'd need to do:
reciprocal(x.toDouble());
You can also use:
int x = 15;
double y = x + .0;
use toDouble() method.
For e.g.:
int a = 10
print(a.toDouble)
//or store value in a variable and then use
double convertedValue = a.toDouble()
From this attempt:
class Useless{
double field;
Useless(num input){
field = input.toDouble();
}
}
You can use the parse method of the double class which takes in a string.
class Useless{
double field;
Useless(num input){
field = double.parse(input.toString()); //modified line
}
}
A more compact way of writing the above class using constructor's initialisers is:
class Useless{
double _field;
Useless(double field):_field=double.parse(field.toString());
}
Since all divisions in flutter result to a double, the easiest thing I did to achieve this was just to divide the integer value with 1:
i.e.
int x = 15;
double y = x /1;
There's no better way to do this than the options you included :(
I get bitten by this lots too, for some reason I don't get any warnings in the editor and it just fails at runtime; mighty annoying :(
I'm using a combination:
static double checkDouble(dynamic value) {
if (value is String) {
return double.parse(value);
} else if (value is int) {
return 0.0 + value;
} else {
return value;
}
}
This is how you can cast from int to double
int a = 2;
double b = a*1.0;
In dart, as I am a newbie using extension, I want to make a simple extension to check value is double.
extension numberExtension on num{
bool get isInteger => (this % 1) == 0;
bool get isDouble =>double.tryParse(this) != null;
}
here isInteger is correct, but for isDouble I get this error:
The argument type 'num' can't be assigned to the parameter type
'String'
Problem is this in isDouble getter!?
Assuming anything that is not an Integer is a Float or a Double;
Why not implement isDecimal instead, something like:
extension numberExtension on num {
bool get isInteger => (this % 1) == 0;
bool get isDecimal => (this % 1) != 0;
}
OR
extension numberExtension on num {
bool get isInteger => this is int;
bool get isDecimal => !(this is int);
}
Note that we could directly use "this is double" above,
but the "!(this is int)" check is simply more change-compatible,
because it would even work if Dart ever adds some new num sub-type.
Update; looking into docs tells us that:
If compiled into JavaScript, there is no real int type, only doubles without decimal.
Dart does not seem to support 32-bit float, but has 64-bit double at least.
int is always 64-bit (just like double), but bitwise and/or shift operators truncate it into 32-bit (losing data or percision).
Replace
double.tryParse(this) != null
with
this is double
Your original approach:
extension numberExtension on num {
bool get isInteger => (this % 1) == 0;
bool get isDouble =>double.tryParse(this) != null;
}
doesn't work because your extension is on num, so this is a num. double.tryParse expects to parse a String.
Why don't you just check if the object is an int or double directly?
extension numberExtension on num {
bool get isInteger => this is int;
bool get isDouble => this is double;
}
Of course, the extension is not very useful since x.isDouble is not much more convenient to use than using x is double directly, and the latter has the benefit of allowing automatic type-promotion to occur.
(Also, for Dart for the web, where int and double types are both backed by JavaScript numbers, numbers can be reported as both int and double, but using heuristics like % 1 and double.tryParse won't help with that.)
Not really understanding why this isn't working. I'm pretty new to the Swift world.
The error I'm getting is Binary operator '>=' cannot be applied to operands of type 'String' and 'Int'
Could anyone help me understand why I'm getting this error? Do I need to convert the String to a Double or is there something else I'm totally missing? Again I'm new to Swift.
Do I need to convert the String to a Double?
Yes, that's basically it.
You must declare first a variable to accumulate all the inputs:
var inputs = [Double]()
Observe that I'm declaring an array of Double because that's what we are interested in.
Then, each time you ask the input, convert the obtained String to Double and store it in your array:
print("Please enter a temperature\t", terminator: "")
var message : String = readLine()!
let value : Double = Double(message)!
inputs.append(value)
Finally, check all the accumulated values in inputs (you got this part right):
for value in inputs {
// value is already a Double
if value >= 80 {
message = "hot!"
}
// etc.
}
I suggest researching how to convert to Double with error checking (i.e. how to detect "100 hot!" and ignore it because can't be converted).
Also, consider using a loop to read the values.
Imagine my surprise that this Swift code generates an error in Xcode 6.1.1:
public func unlockNextLevel() -> Int
{
var highest : Int = 123
return (highest < highestUnlockedLevel)
}
More precisely, it tells me that in the return line:
'Int' is not convertible to 'String'
So, since I had some of these weird conversion errors before, I thought I'll try converting both types to Int and see what I get:
public func unlockNextLevel() -> Int
{
var highest : Int = 123
return (Int(highest) < Int(highestUnlockedLevel))
}
I then get the following error on the return line:
Could not find an overload for '<' that accepts the supplied arguments
But when I break it down to just constant values:
return (Int(3) < Int(12))
I get the int not convertible to string error again.
'Int' is not convertible to 'String'
Gnnnnn.... oh-kay, so I give it another shot without the brackets:
return highest < highestUnlockedLevel
This then gives me yet another error message:
Cannot invoke '<' with an argument list of type '(#lvalue Int, #lvalue Int)'
Okay, I get it Swift, I'm stoopid. Or maybe ... hmmm, take this, Swift:
var result = highest < highestUnlockedLevel
return result
Arrrr ... nope. Swift decides that now the return line constitutes yet another error:
'Bool' is not convertible to 'Int'
(... dials number for psych evaluation ...)
So ... could someone explain to me:
how to fix or work around this issue?
and of course: Why?? Oh, why???
Note: This is in a mixed Objc/Swift project if that makes any difference. The highestUnlockedLevel variable is declared in a Swift class with custom setter and getter.
(highest < highestUnlockedLevel) produces Bool not Int (unlike Objective-C where it returns int that can be automatically converted to BOOL), thats why you get the error. But certainly its wrong and misleading error as the problem is that Bool cannot be converted to Int.