How do you use parse string in swift? - ios

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)

Related

How to convert sequence of ASCII code into string in swift 4?

I have an sequence of ASCII codes in string format like (7297112112121326610511411610410097121). How to convert this into text format.
I tried below code :
func convertAscii(asciiStr: String) {
var asciiString = ""
for asciiChar in asciiStr {
if let number = UInt8(asciiChar, radix: 2) { // Cannot invoke initializer for type 'UInt8' with an argument list of type '(Character, radix: Int)'
print(number)
let character = String(describing: UnicodeScalar(number))
asciiString.append(character)
}
}
}
convertAscii(asciiStr: "7297112112121326610511411610410097121")
But getting error in if let number line.
As already mentioned decimal ASCII values are in range of 0-255 and can be more than 2 digits
Based on Sulthan's answer and assuming there are no characters < 32 (0x20) and > 199 (0xc7) in the text this approach checks the first character of the cropped string. If it's "1" the character is represented by 3 digits otherwise 2.
func convertAscii(asciiStr: String) {
var source = asciiStr
var result = ""
while source.count >= 2 {
let digitsPerCharacter = source.hasPrefix("1") ? 3 : 2
let charBytes = source.prefix(digitsPerCharacter)
source = String(source.dropFirst(digitsPerCharacter))
let number = Int(charBytes)!
let character = UnicodeScalar(number)!
result += String(character)
}
print(result) // "Happy Birthday"
}
convertAscii(asciiStr: "7297112112121326610511411610410097121")
If we consider the string to be composed of characters where every character is represented by 2 decimal letters, then something like this would work (this is just an example, not optimal).
func convertAscii(asciiStr: String) {
var source = asciiStr
var characters: [String] = []
let digitsPerCharacter = 2
while source.count >= digitsPerCharacter {
let charBytes = source.prefix(digitsPerCharacter)
source = String(source.dropFirst(digitsPerCharacter))
let number = Int(charBytes, radix: 10)!
let character = UnicodeScalar(number)!
characters.append(String(character))
}
let result: String = characters.joined()
print(result)
}
convertAscii(asciiStr: "7297112112121326610511411610410097121")
However, the format itself is ambigious because ASCII characters can take from 1 to 3 decimal digits, therefore to parse correctly, you need all characters to have the same length (e.g. 1 should be 001).
Note that I am taking always the same number of letters, then convert them to a number and then create a character the number.

How do I extract any number of digits after the decimal point of a Float and convert it to a String in Swift?

Basically, I have a Float, for example: 3.511054256.
How can I extract n number of digits after the decimal point?
i.e. I'd like to retrieve 0.51, 0.511, 0.5110 or etc.
I know I can easily achieve something like this:
var temp: Float = 3.511054256
var aStr = String(format: "%f", temp)
var arr: [AnyObject] = aStr.componentsSeparatedByString(".")
var tempInt: Int = Int(arr.last as! String)!
However, this gives me 511054. I'd like the option of retrieving any number of digits past the decimal point easily.
For a task I'm doing, I only need to retrieve the first 2 digits after the decimal point, but less restriction would be ideal.
Thanks.
You can specify the number of decimal digits, say N, in your format specifier as %.Nf, e.g., for 5 decimal digits, %.5f.
let temp: Float = 3.511054256
let aStr = String(format: "%.5f", temp).componentsSeparatedByString(".").last ?? "Unexpected"
print(aStr) // 51105
Alternatively, for a more dynamic usage, make use of an NSNumberFormatter:
/* Use NSNumberFormatter to extract specific number
of decimal digits from your float */
func getFractionDigitsFrom(num: Float, inout withFormatter f: NSNumberFormatter,
forNumDigits numDigits: Int) -> String {
f.maximumFractionDigits = numDigits
f.minimumFractionDigits = numDigits
let localeDecSep = f.decimalSeparator
return f.stringFromNumber(num)?.componentsSeparatedByString(localeDecSep).last ?? "Unexpected"
}
/* Example usage */
var temp: Float = 3.511054256
var formatter = NSNumberFormatter()
let aStr = getFractionDigitsFrom(temp, withFormatter: &formatter, forNumDigits: 5)
print(aStr) // 51105
Note that both solutions above will perform rounding; e.g., if var temp: Float = 3.519, then asking for 2 decimal digits will produce "52". If you really intend to treat your float temp purely as a String (with no rounding whatsoever), you could solve this using just String methods, e.g.
/* Just treat input as a string with known format rather than a number */
func getFractionDigitsFrom(num: Float, forNumDigits numDigits: Int) -> String {
guard let foo = String(temp).componentsSeparatedByString(".").last
where foo.characters.count >= numDigits else {
return "Invalid input" // or return nil, for '-> String?' return
}
return foo.substringWithRange(foo.startIndex..<foo.startIndex.advancedBy(numDigits))
}
/* Example usage */
let temp: Float = 3.5199
let aStr = getFractionDigitsFrom(temp, forNumDigits: 2) // 51

Multiply UITextfields values with Double in Swift?

I am trying to Multiply
self.tipLable.text = String("\((enterBillAmountTextField.text! as NSString).integerValue * (middleTextField.text! as NSString).integerValue * (0.01))")
But getting error Binary operator * cannot be applied to operands of type Int and Double
I am taking values form UITextfields. How to do this multiplication?
extension Double {
// Convert Double to currency
var currency: String {
let formatter = NSNumberFormatter()
formatter.numberStyle = .DecimalStyle
formatter.maximumFractionDigits = 2
formatter.minimumFractionDigits = 2
return formatter.stringFromNumber(self) ?? "0"
}
}
tipLable.text = [enterBillAmountTextField, middleTextField].reduce(0.01) { $0 * (Double($1.text!) ?? 0) }.currency
A slightly shorter and clearer solution. Added a "currency" extension so it can still be done in one line :).
This works
self.tipLable.text = String("\( Double((enterBillAmountTextField.text! as NSString).integerValue) * Double((middleTextField.text! as NSString).integerValue) * 0.01)")
Swift doesn't know how to multiply an Int and a Double. Should the result be an Int or a Double?
Swift won't do implicit type conversion between different operands.
If you want your result to be a Double, both operands should be a Double. Then convert the Double to a String.
While this can all be concisely expressed in one single very long line, perhaps it's more readable and maintainable if you break it out into separate lines:
let subTotal = Double(billAmountTextField.text!) ?? 0
let percent = (Double(middleTextField.text!) ?? 0) * 0.01
let tip = subTotal * percent
self.tipLable.text = String(format: "%.2f", tip) // Handle rounding
The answer you gave is going to bring nightmare to you in some moment.
Try to keep yourself doing things in a way you can guarantee that you are going to be able to test it and that you/or others are going to be able to understand what you are doing there.
/**
Use this function to calculate tip, useful for later testing
- returns: Double Value of the tip you should give
*/
func calculateTip(billAmount billAmount:Double, middleValue:Double) -> Double {
/// Actually calculate Tip if everything is OK
return billAmount * middleValue * 0.01
}
Then in your #IBAction make sure you have correct data before asking
your function for a tip
/// If you have bill data, obtain Double value stored there,
/// if something fails, you should return nil
guard let billAmountText = enterBillAmountTextField.text, billAmount = Double(billAmountText) else {
return
}
/// If you have middle value data, obtain Double value stored there,
/// if something fails, you should return nil
guard let middleText = middleTextField.text, middleValue = Double(middleText) else {
return
}
Then you can call that function
let tip = calculateTip(billAmount: billAmount, middleValue: middleValue).description
//and return in proper format
tipLabel.text = String(format: "%.2f", tip)

concatenating NSString and Int in Apple Swift

I have used arc4random_uniform() to get the random values from given String or Int. Now I want to join those to values.
var randomNumber = arc4random_uniform(9999) + 1000 // returns random number between 1000 and 9999 e.g. - 7501
let alphabet_array = ["A","B","C","D","E","F","G","H","I","J","K","L","M","N","O","P","Q","R","S","T","U","V","W","X","Y","Z"]
let randomIndex = Int(arc4random_uniform(UInt32(alphabet_array.count)))
let random_alphabet = alphabet_array[randomIndex] // returns random alphabet e.g. - E
What I want is to display 7501 and E together like 7501E
var str="\(randomNumber)\(random_alphabet)" // error
I am getting below error :
Command /Applications/Xcode6-Beta.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/bin/swift failed with exit code 254
Please help how can I display this together.
It works fine with the right punctuation:
var randomNumber = arc4random_uniform(999) + 1000
// returns random number between 1000 and 9999 e.g. - 7501 NOTE 999 not 9999
let alphabet_array = ["A","B","C","D","E","F","G","H","I","J","K","L","M","N","O","P","Q","R","S","T","U","V","W","X","Y","Z"]
// Note missing "=" in OP
let randomIndex = Int(arc4random_uniform(UInt32(alphabet_array.count)))
let random_alphabet = alphabet_array[randomIndex] // returns random alphabet e.g. - E
var str = "\(randomNumber)\(random_alphabet)" // e.g. 1197A
Instead of using string interpolation, you could also convert the random number to a string and just add them together:
let str = randomNumber.description + random_alphabet

Actionscript parse currency to get a number

i used a CurrencyFormatter to parse 2 number into its currency representation
currencyFormat.format("10" + "." + "99") ---> $10.99
I'm curious if there is a way to parse a string "$10.99" back to a number / double ?
so it is possible to get the value on the left side of the decimal and right side of the decimal.
thanks,
You could do this a number of ways. Here are 2 off the top of my head:
function currencyToNumbers($currency:String):Object {
var currencyRE:RegExp = /\$([1-9][0-9]+)\.?([0-9]{2})?/;
var val = currencyRE.exec($currency);
return {dollars:val[1], cents:val[2]};
}
function currencyToNumbers2($currency:String):Object {
var dollarSignIndex:int = $currency.indexOf('$');
if (dollarSignIndex != -1) {
$currency = $currency.substr(dollarSignIndex + 1);
}
var currencyParts = parseFloat($currency).toString().split(".");
return {dollars:currencyParts[0], cents:currencyParts[1]};
}
var currency:Object = currencyToNumbers('$199.99');
trace(currency.dollars);
trace(currency.cents);
var currency2:Object = currencyToNumbers2('$199.99');
trace(currency2.dollars);
trace(currency2.cents);

Resources