Convert a float into a string in Swift iOS - ios

I want to convert a Float into a string.
myFloat: Float = 99.0
myString: String
How would I convert myFloat into a string so I can assign the following code
myString = myFloat

Similar to Connor's answer, you can do the following to have a little more control about how your Double or Float is dislpayed...
let myStringToTwoDecimals = String(format:"%.2f", myFloat)
This is basically like stringWithFormat in objC.

You can use String Interpolation:
var myFloat: Float = 99.0
var myString: String = "\(myFloat)"

Related

Dart convert int variable to string

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.

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!)

length (byte-wise) of a string in swift 2.2

How do we find out the length (byte-wise) of a string [declared String type, not NSString] in Swift 2.2?
I know one way out is to use _bridgeToObejectiveC().length
Is there any other way out?
let str: String = "Hello, World"
print(str.characters.count) // 12
let str1: String = "Hello, World"
print(str1.endIndex) // 12
let str2 = "Hello, World"
NSString(string: str2).length //12
Refer String length in Swift 1.2 and Swift 2.0 and Get the length of a String
let str: String = "Hello, World"
print(str.characters.count) // 12
let byteLength = str.lengthOfBytesUsingEncoding(NSUTF8StringEncoding)
print("byte lenght: \(byteLength)")//12
let str2: String = "你好"
print(str2.characters.count) // 2
let byteLength2 = str.lengthOfBytesUsingEncoding(NSUTF8StringEncoding)
print("byte lenght: \(byteLength2)")//12
Try this code:
Swift
let test : String = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
let bytes : NSInteger = test.lengthOfBytesUsingEncoding(NSUTF8StringEncoding);
NSLog("%i bytes", bytes);
Objective C
refer this link:
What is the length in bytes of a NSString?
I think type casting is another easier way to use the methods, properties of NSString class.
print((str as NSString).length)

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)

String to Double in XCode 6's Swift [duplicate]

This question already has answers here:
Swift - How to convert String to Double
(30 answers)
Closed 7 years ago.
How do I convert a string to double in Swift? I've tried string.doubleValue or string.bridgeToObjectiveC().doubleValue and none of it works. Any ideas?
You can create a read-only computed property string extension to help you convert your strings to double:
You can use NSNumberFormatter
extension String {
struct Number {
static let formatter = NSNumberFormatter()
}
var doubleValue: Double {
return Number.formatter.numberFromString(self)?.doubleValue ?? 0
}
}
or you can cast it to NSString and extract its doubleValue property:
extension String {
var ns: NSString {
return self
}
var doubleValue: Double {
return ns.doubleValue
}
}
"2.35".doubleValue + 3.3 // 5.65
According to Stanford CS193p course Winter 2015, the correct way to get a double from a String in Swift is to use NSNumberFormatter instead of NSString:
let decimalAsString = "123.45"
let decimalAsDouble = NSNumberFormatter().numberFromString(decimalAsString)!.doubleValue
If you want to be safe (regarding the optional unwrapping and the decimal separator), you'd use:
let decimalAsString = "123.45"
var formatter = NSNumberFormatter()
formatter.locale = NSLocale(localeIdentifier: "en_US")
if let decimalAsDoubleUnwrapped = formatter.numberFromString(decimalAsString) {
decimalAsDouble = decimalAsDoubleUnwrapped.doubleValue
}
Safe unwrapping is particularly useful if you parse a XML or JSON file and you need to make sure you have a String that can be converted into a Double (the program will crash if you force-unwrap an optional that is actually nil).
/!\
EDIT: be careful, NSNumberFormatter works differently than NSString.
NSString allowed you to do things like : (dictionary[key] as NSString).doubleValue, provided that dictionary[key] used the '.' as decimal separator (like in "123.45").
But NSNumberFormatter(), by default, initializes an instance of NSNumberFormatter with your current system Locale!
Therefore, NSNumberFormatter().numberFromString(decimalAsString)!.doubleValue would work with 123.45 on a US device, but not on a French one for example!
If you are parsing a JSON file for example, and you know that values are stored using '.' as the decimal separator, you need to set the locale of your NSNumberFormatter instance accordingly:
var formatter = NSNumberFormatter()
formatter.locale = NSLocale(localeIdentifier: "en_US")
then:
let decimalAsString = "123.45"
if let decimalAsDoubleUnwrapped = NSNumberFormatter().numberFromString(decimalAsString) {
decimalAsDouble = decimalAsDoubleUnwrapped.doubleValue
}
In that case, decimalAsDouble will correctly return 123.45 as a doubleValue.
But it would return nil if decimalAsString = "123,45".
Or if the NSLocale was set as "fr_FR".
On the other hand, a NSNumberFormatter using a NSLocale with fr_FR would work perfectly with "123,45", but return nil with "123.45".
I thought that was worth reminding.
I updated my answer accordingly.
EDIT : also, NSNumberFormatter wouldn't know what do with things like "+2.45%" or "0.1146"(you would have to define the properties of your NSNumberFormatter instance very precisely). NSString natively does.
you can always just cast from String to NSString like this
let str = "5"
let dbl = (str as NSString).doubleValue
Try this :
var a:Double=NSString(string: "232.3").doubleValue
Try this:
let str = "5"
let double = Double(str.toInt()!)
another way is:
let mySwiftString = "5"
var string = NSString(string: mySwiftString)
string.doubleValue
this latter one posted here:
Swift - How to convert String to Double

Resources