Dart convert int variable to string - dart

I'm trying to convert an integer variable
var int counter = 0;
into a string variable
var String $counter = "0";
I searched but I only found something like
var myInt = int.parse('12345');
that doesn't work with
var myInt = int.parse(counter);

Use toString and/or toRadixString
int intValue = 1;
String stringValue = intValue.toString();
String hexValue = intValue.toRadixString(16);
or, as in the commment
String anotherValue = 'the value is $intValue';

// String to int
String s = "45";
int i = int.parse(s);
// int to String
int j = 45;
String t = "$j";
// If the latter one looks weird, look into string interpolation on https://dart.dev

You can use the .toString() function in the int class.
int age = 23;
String tempAge = age.toString();
then you can simply covert integers to the Strings.

Related

Not able to access values from dictionary

I have a dictionary like so..
{
"Due_Date" = "2020-06-09T15:00:13";
departmentID = 180075;
keyPointID = "";
id = 4;
jobID = 180093;
jobName = myLab;
plantID = 1232;
shiftID = 2;
"smat_Leader1ID" = 43232;
workshopID = 423423;
workstationID = 1892074;
}
I'm not able to get any values except those values whose key and value is string (Like Due_Date). I have fetched it like so...
var Due_Date = self.dictionary["Due_Date"]! as? String //This gives an answer
Similarely, if I try to fetch these values, I don't get the values
var Department_ID = self.dictionary["departmentID"]! as? Int ?? 0 //This gives 0
var smatLeader1ID = self.dictionary["smat_Leader1ID"]! as? Int ?? 0 //This gives 0
(I don't get the other values also. Just that I mentioned just 2 above)
Since you're force casting and not getting a crash you seem to be getting the value but you're trying to cast the value as Int which is failing here. Seems the value is not an Int type could be String try out this to fix it.
Replace this:
var Department_ID = self.dictionary["departmentID"]! as? Int ?? 0
With this:
var Department_ID = Int(self.dictionary["departmentID"] as? String ?? "0")

Convert string (float value) to int in Swift

Hello I have string "(with float value)"
let floatstring : String = "23.24"
print(floatstring)
I want to convert float String to Int.
Thank you !
Option 1
let intNum = Int(Float(floatstring)!)
Option 2
if floatstring.rangeOfString(".") != nil {
let i = Int(floatstring.componentsSeparatedByString(".").first!)
print(i)
}
It should work like this:
http://swiftlang.ng.bluemix.net/#/repl/57bd6566b36620d114f80313
let floatstring : String = "23.24"
print(Int(Float(floatstring)!))
You can cast the String to a Float and then to an Int.
if let floatValue = Float(floatString) {
if let intValue = Int(floatValue) {
print(intValue) //that is your Int
}
}
If it does not print anything then the string is not a 'floatString'.
Btw you can simply find the answer by combining the answers to these Questions.
Stackoverflow: String to Int
Stackoverflow: Casting Float to Int
1.For Swift 2.0
let intValue=int(float(floatString))
2.For Older version of Swift
let floatValue = (floatString.text as NSString).floatValue
let intValue:Int? = Int(floatValue)
3.For objective-C
floatValue = [floatString floatValue];
int intValue:Int = (int) floatValue;
Try This
let floatValue = "23.24".floatValue // first convert string to float
let intValue:Int? = Int(floatValue) // then convert float to int
print(intValue!)

How to cast numeric types?

I am using Xcode playground to downcast in swift. Typecasting would normally allow me to convert a type to derived type using As operator in swift. But it gives me error while i try to typecast var a as Double,String. Thanks in advance!!
var a = 1
var b = a as Int
var c = a as Double
var d = a as String
You cannot cast it to each other because they do not relate. You can only cast types that are related like UILabel and UIView or [AnyObject] and [String]. Casting an Int to a Double would be like trying to cast a CGPoint to a CGSize
So to change for example an Int to a Double you have to make a new Double of that Int by doing Double(Int).
This applies to all numeric types like UInt Int64 Float CGFloat etc.
Try this:
var a = 1
var b = Int(a)
var c = Double(a)
var d = String(a)
Cast as Int works, because a is Int
You should do it like this:
var c = Double(a)
var d = toString(a) //or String(a)

How do you use parse string in swift?

An issue here to me that if i use parse string for the result of calculator program for instance,
4.5 * 5.0 = 22.5
how can I use splitting here to depart decimal part from result?
Assuming you're working with strings only :
var str = "4.5 * 5.0 = 22.5 "
// Trim your string in order to remove whitespaces at start and end if there is any.
var trimmedStr = str.stringByTrimmingCharactersInSet(NSCharacterSet.whitespaceCharacterSet())
// Split the string by " " (whitespace)
var splitStr = trimmedStr.componentsSeparatedByString(" ")
// If the split was successful, retrieve the last past (your number result)
var lastPart = ""
if let result = splitStr.last {
lastPart = result
}
// Since it's a XX.X number, split it again by "." (point)
var splitLastPart = lastPart.componentsSeparatedByString(".")
// If the split was successful, retrieve the last past (your number decimal part)
var decimal = ""
if let result = splitLastPart.last {
decimal = result
}
Use modf to extract decimal part from result.
Objective-C :
double integral = 22.5;
double fractional = modf(integral, &integral);
NSLog(#"%f",fractional);
Swift :
var integral:Double = 22.5;
let fractional:Double = modf(integral,&integral);
println(fractional);
Want only interger part from double of float
Want only integer value from double then
let integerValue:Int = Int(integral)
println(integerValue)
Want only integer value from float then
let integerValue:Float = Float(integral)
println(integerValue)

How to Tokenize String with Commas and Line Delimiter

I'm making a simple String Tokenizer in Swift like I would in Java...but it's really not working out for me.
The end of each line in my data source delimited with "^" and the data is separated by comma's.
For example: "string 1,string 2,string 3,^,string 1,string 2,string 3,^"
This is what I would do in Java...(I only want the first two strings in each line of data)
String delimeter = "^";
StringTokenizer tokenizedString = new StringTokenizer(responseString,delimeter);
String [] stringArray = new String [tokenizedString.countTokens()];
StringTokenizer tokenizedAgain;
String str1;
String str2;
String token;
for(int i =0; i< stringArray.length; i ++)
{
token = tokenizedString.nextToken();
tokenizedAgain = new StringTokenizer(token, ",");
tokenizedAgain.nextToken();
str1 = tokenizedAgain.nextToken();
str2 = tokenizedAgain.nextToken();
}
If someone could point me in the right direction that would really helpful.
I've looked at this: Swift: Split a String into an array
and this: http://www.swift-studies.com/blog/2014/6/23/a-swift-tokenizer
but I can't really find other resources on String Tokenizing in Swift. Thanks!
This extends Syed's componentsSeperatedByString answer but with Swift's map to create the requested Nx2 matrix.
let tokenizedString = "string 1, string 2, string 3, ^, string a, string b, string c, ^"
let lines = tokenizedString.componentsSeparatedByString("^, ")
let tokens = lines.map {
(var line) -> [String] in
let token = line.componentsSeparatedByString(", ")
return [token[0], token[1]]
}
println(tokens)
var delimiter = "^"
var tokenDelimiter = ","
var newstr = "string 1, string 2, string 3, ^, string 1, string 2, string 3,^"
var line = newstr.componentsSeparatedByString(delimiter) // splits into lines
let nl = line.count
var tokens = [[String]]() // declares a 2d string array
for i in 0 ..< nl {
let x = line[i].componentsSeparatedByString(tokenDelimiter) // splits into tokens
tokens.append(x)
}
println(tokens[0][0])

Resources