I have converted a String to an Int by by using toInt(). I then tried multiplying it by 0.01, but I get an error that says Could not find an overload for '*' that accepts the supplied argument. Here is my code:
var str: Int = 0
var pennyCount = 0.00
str = pennyTextField.text.toInt()!
pennyCount = str * 0.01
From reading other posts it seems that the answer has to do with the type. For example if the type is set as an Integer then it gets a similar error. I have tried changing the type to an Int, but that doesn't seem to solve the problem.
I have also tried setting the type for 'str' and 'pennyCount' as Floats and Doubles and all combinations of Floats, Doubles, and Ints. My guess is the the problem has to do with toInt() function's conversion of a String to an Integer.
Could someone help clarify what the issue may be?
Swift seems to be fairly picky about implied type casting, so in your example you're multiplying str (an Integer) by 0.01 (a Double) so to resolve the error, you'll need to cast it like this:
var str: Int = 0
var pennyCount = 0.00
str = pennyTextField.text.toInt()!
pennyCount = Double(str) * 0.01
Related
Hi so i have a double seems like this
d1 = 12.106
and i need to show in to a string '12.130'
double num1 = double. parse((12.3404). toStringAsFixed(3));
well i expected to return "12.130" but it returned "12.13"
the thing i need a string "12.130" instead "12.13"
double num1 = double. parse((12.3404). toStringAsFixed(4));
so tried this one again but also failed
well then number must be shown 3 decimals even if the last is 0
where or what should i have to fix?
I understand you have the following variable:
double d = 12.130;
and now you want to convert it to a string with the following value: String s = "12.130"
This should work:
String res = d.toStringAsFixed(3) //"12.130"
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;
I am trying to generate a random number in Swift:
var amountOfQuestions = 2
var randomNumber = Int(arc4random_uniform(amountOfQuestions - 1)) + 1
but this results in the error:
Cannot convert value of type 'Int' to expected argument type 'UInt32'
What is the problem? Any ideas on what I can do to fix this error?
Declare amountOfQuestions as a UInt32:
var amountOfQuestions: UInt32 = 2
PS: If you want to be grammatically correct it's number of questions.
First thing:
The method "arc4random_uniform" expects an argument of type UInt32, so when you put that subtraction there, it converted the '1' you wrote to UInt32.
Second thing: In swift you can't subtract a UInt32 (the '1' in your formula) from an Int (in this case 'amountOfQuestions').
To solve it all, you'll have to consider changing the declaration of 'amountOfQuestions' to:
var amountOfQuestions = UInt32(2)
That should do the trick :)
Make your amountOfQuestions variable an UInt32 rather than an Int inferred by the compiler.
var amountOfQuestions: UInt32 = 2
// ...
var randomNumber = Int(arc4random_uniform(amountOfQuestions - 1)) + 1
arc4random_uniform requires a UInt32.
From the Darwin docs:
arc4random_uniform(u_int32_t upper_bound);
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
I've been trying out Swift, since it's obviously the direction that Apple wants us to go in.
However, I've been really annoyed with the fact that you can't seem to add integers of different sizes:
var a: Int64 = 1500
var b: Int32 = 12349
var c = a + b
if a < b { ... }
The yielded error is "Could not find an overload for '+' that accepts the supplied argument' — obviously since they are object types. None of the class methods seem to be of any help in up/down-converting integers.
Same situation applies with any of the type aliases, obviously, (CInt + CLong).
I can see a lot of real-world situations where it is immensely practical to be able to do integer arithmetic let alone comparisons or bitwise operations on two disparately-sized integers.
How to solve this? Explicit casting with the as operator doesn't seem to work. The Swift language book isn't much help either as it doesn't really discuss this scenario.
The Swift language book does discuss this scenario in the chapter “Numeric Type Conversion”:
let twoThousand: UInt16 = 2_000
let one: UInt8 = 1
let twoThousandAndOne = twoThousand + UInt16(one)
Because both sides of the addition are now of type UInt16, the addition is allowed. The output constant (twoThousandAndOne) is inferred to be of type UInt16, because it is the sum of two UInt16 values.
let a: Int64 = 1500
let b: Int32 = 12349
let c = a + Int64(b)
println("The value of c is \(c)")