Convert string (float value) to int in Swift - ios

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

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.

How to convert from unichar to character

There is better way to convert from unichar to Character?
tried :
var unichar = ...
let str = NSString(characters: &unichar, length: 1) as String
let character = Array(str.characters)[0])
You can convert unichar -> UnicodeScalar -> Character:
let c = unichar(8364)
if let uc = UnicodeScalar(c) {
let char = Character(uc)
print(char) // €
} else {
print("illegal input")
}
Input values in the range 0xD800...0xDFFF
(high and low surrogates) are not allowed because they do not
correspond to valid Unicode scalar values.
If it is guaranteed that those input values do not occur then you
can simplify the conversion to
let char = Character(UnicodeScalar(c)!)
To replace a possible invalid input value by a default character
(e.g. a question mark), use
let char = Character(UnicodeScalar(c) ?? "?")
public class func stringForIcon(_ icon: NSInteger) -> Character {
return Character(UnicodeScalar(icon)!)
}

Swift 3 : Decimal to Int

I tried to convert Decimal to Int with the follow code:
Int(pow(Decimal(size), 2) - 1)
But I get:
.swift:254:43: Cannot invoke initializer for type 'Int' with an argument list of type '(Decimal)'
Here I know pow is returning a Decimal but it seems that Int has no constructors and member functions to convert Decimal to Int.
How can I convert Decimal to Int in Swift 3?
This is my updated answer (thanks to Martin R and the OP for the remarks). The OP's problem was just casting the pow(x: Decimal,y: Int) -> Decimal function to an Int after subtracting 1 from the result. I have answered the question with the help of this SO post for NSDecimal and Apple's documentation on Decimal. You have to convert your result to an NSDecimalNumber, which can in turn be casted into an Int:
let size = Decimal(2)
let test = pow(size, 2) - 1
let result = NSDecimalNumber(decimal: test)
print(Int(result)) // testing the cast to Int
let decimalToInt = (yourDecimal as NSDecimalNumber).intValue
or as #MartinR suggested:
let decimalToInt = NSDecimalNumber(decimal: yourDecimal).intValue
If you have a very long decimal, then beware of rounding errors
let decimal = Decimal(floatLiteral: 100.123456)
let intValue = (decimal as NSDecimalNumber).intValue // This is 100
However
let veryLargeDecimal = Decimal(floatLiteral: 100.123456789123)
let intValue = (veryLargeDecimal as NSDecimalNumber).intValue // This is -84 !
I ensured I rounded my Decimal before I converted it to an Int, using NSDecimalRound (which you can put in an extension of Decimal).
var veryLargeDecimal = Decimal(floatLiteral: 100.123456789123)
var rounded = Decimal()
NSDecimalRound(&rounded, &veryLargeDecimal, 0, .down)
let intValue = (rounded as NSDecimalNumber).intValue // This is now 100
There is nothing wrong with either of the posted answers, but I would like to offer up an extension that reduces the verbosity for scenarios where you need to use this frequently.
extension Decimal {
var int: Int {
return NSDecimalNumber(decimal: self).intValue
}
}
To call it:
let powerDecimal = pow(2, 2) // Output is Decimal
let powerInt = powerDecimal.int // Output is now an Int
Unfortunately there is an intermittent failure using some of the methods provided.
NSDecimalNumber(decimal: <num>).intValue can produce unexpected results...
(lldb) po NSDecimalNumber(decimal: self)
10.6666666666666666666666666666666666666
(lldb) po NSDecimalNumber(decimal: self).intValue
0
I think there is more of a discussion on it here, and #Martin was pointing it out here
Instead of using the decimal value directly, I made a work around that converts the decimal to a whole number before converting the Decimal to an Int.
extension Decimal {
func rounded(_ roundingMode: NSDecimalNumber.RoundingMode = .down, scale: Int = 0) -> Self {
var result = Self()
var number = self
NSDecimalRound(&result, &number, scale, roundingMode)
return result
}
var whole: Self { rounded( self < 0 ? .up : .down) }
var fraction: Self { self - whole }
var int: Int {
NSDecimalNumber(decimal: whole).intValue
}
}
Just use the description of Decimal, String replacement the NSDecimalNumber to bridge it.
extension Decimal {
var intVal: Int? {
return Int(self.description)
}
}

What is the difference between " as string" and "stringvalue" in swift?

I have a code :
var i : AnyObject!
i = 10
println(i as String)
println(i.stringValue)
it get crashed on as String line but runs in second i.stringValue.
What is the difference between as String and stringValue in the above lines?
.stringValue is a way to extract Integer into string value but as String will not work for that And if you use as String then Xcode will force you to add ! with as which is not good and it will never succeed and it would crash your app. you can't cast Int to String. It will always fail. Thats why when you do as! String it crashes the app.
So casting is not a good idea here.
And here is some more ways to extract Integer into string value:
let i : Int = 5 // 5
let firstWay = i.description // "5"
let anotherWay = "\(i)" // "5"
let thirdWay = String(i) // "5"
Here you can not use let forthway = i.stringValue because Int Doesn't have member named stringValue
But you can do same thing with anyObject as shown below:
let i : AnyObject = 5 // 5
let firstWay = i.description // "5"
let anotherWay = "\(i)" // "5"
let thirdWay = String(i) // "5"
let forthway = i.stringValue // "5" // now this will work.
Both are casting an Int to String but this will not work anymore.
In Swift 2 its not possible to do it like that.
U should use:
let i = 5
print(String(format: "%i", i))
This will specifically write the int value as a String
with as String, you can not cast the value but you define that the variable contains String but in you case it is Int.so it crashes.
while the other way i.e. of i.stringValue cast your value into String.So it doesn't gives you any crash and successfully cast into String value.
Note: As you are using AnyObject, variable have member stringvalue...but Int doesn't have...To cast Int value check out #Dharmesh Kheni answer

Convert a float into a string in Swift 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)"

Resources