How to display the string without 0 - ios

I try to eliminate the 0 at the end of string. right now what i have is (Return "2101999.0000")
let point = newObject["PtsBal"] as! String
i use
NSNumberRFormatter()
but i dont know where i did wrong. i need to display it back in this as a string.
self.detailArr = ["\((self.userInfo!["FirstName"] as! String).capitalizedString) \((self.userInfo!["LastName"] as! String).capitalizedString)", point, ""]

try this
let point = newObject["PtsBal"] as! String
let formatter = NSNumberFormatter()
formatter.numberStyle = .DecimalStyle
if let number = formatter.numberFromString(point) {
// number is an instance of NSNumber
point = String(number.integerValue)
}
you get the output as
finally append the string where you need
self.detailArr = ["\((self.userInfo!["FirstName"] as! String).capitalizedString) \((self.userInfo!["LastName"] as! String).capitalizedString)", point, ""]

You can simply remove all characters after (.) dot
var str = "2101999.0000"
if let dotRange = str.rangeOfString(".") {
str.removeRange(dotRange.startIndex..<str.endIndex)
}

Use this single line of Code
let number : Int = NSString(string: YourString).integerValue

Assuming point is always a string representing a floating point value you could use
let point = "2101999.0000"
let number = "\(Int(Double(point)!))"

let string = "2101999.0000"
let result = string.characters.split{$0 == "."}.map(String.init)
print (result[0])

Related

Swift, converting a number to string, number gets rounded down

I'm having a bit of issue with my code...right now, I am passing a string containing a bunch of numbers, to get converted to a number, comma separators added, then converted back to a string for output. When I add a decimal to my string and pass it in, a number like 996.3658 get truncated to 996.366...
"currentNumber" is my input value, "textOutputToScreen" is my output...
func formatNumber() {
let charset = CharacterSet(charactersIn: ".")
if let _ = currentNumber.rangeOfCharacter(from: charset) {
if let number = Float(currentNumber) {
let numberFormatter = NumberFormatter()
numberFormatter.numberStyle = .decimal
guard let formattedNumber = numberFormatter.string(from: NSNumber(value: number)) else { return }
textOutputToScreen = String(formattedNumber)
}
}
else {
if let number = Int(currentNumber) {
let numberFormatter = NumberFormatter()
numberFormatter.numberStyle = .decimal
guard let formattedNumber = numberFormatter.string(from: NSNumber(value: number)) else { return }
textOutputToScreen = String(formattedNumber)
}
}
}
Thank you in advance for your help!
The issue there is that you have to set your NumberFormatter minimumFractionDigits to 4. Btw there is no need to initialize a NSNumber object. You can use Formatters string(for: Any) method and pass your Float. Btw I would use a Double (64-bit) instead of a Float (32-bit) and there is no need to initialize a new string g from your formattedNumber object. It is already a String.
Another thing is that you don't need to know the location of the period you can simply use contains instead of rangeOfCharacter method. Your code should look something like this:
extension Formatter {
static let number: NumberFormatter = {
let formatter = NumberFormatter()
formatter.numberStyle = .decimal
return formatter
}()
}
func formatNumber(from string: String) -> String? {
if string.contains(".") {
guard let value = Double(string) else { return nil }
Formatter.number.minimumFractionDigits = 4
return Formatter.number.string(for: value)
} else {
guard let value = Int(string) else { return nil }
Formatter.number.minimumFractionDigits = 0
return Formatter.number.string(for: value)
}
}
let label = UILabel()
let currentNumber = "996.3658"
label.text = formatNumber(from: currentNumber) // "996.3658\n"
If you would like to assign the result to your var instead of a label
if let formatted = formatNumber(from: currentNumber) {
textOutputToScreen = formatted
}

Search and extract substring in Swift 3

Relatively new to Swift programming.
I get an dictionary from which I need to get the user name (first and last name) and display it in table view cell along with other data.
On iPhone 5 and below as the screen width is only 320, the requirement is to just display the first name and first character of the last name.
E.g: "Howard Mark" to "Howard M"
I am sure that there is an elegant way to extract the required string.
struct ScreenSize
{
static let SCREEN_WIDTH = UIScreen.main.bounds.size.width
static let SCREEN_HEIGHT = UIScreen.main.bounds.size.height
static let SCREEN_MAX_LENGTH = max(ScreenSize.SCREEN_WIDTH, ScreenSize.SCREEN_HEIGHT)
static let SCREEN_MIN_LENGTH = min(ScreenSize.SCREEN_WIDTH, ScreenSize.SCREEN_HEIGHT)
}
struct DeviceType
{
static let IS_IPHONE_5_OR_LESS = (UIDevice.current.userInterfaceIdiom == .phone && ScreenSize.SCREEN_MAX_LENGTH <= 568.0)
}
func functionCall (referralData:[String: Any?])
{
var myMutableString = NSMutableAttributedString()
if var nameString = referralData[KEY_FULL_NAME]
{
if DeviceType.IS_IPHONE_5_OR_LESS
{
var a = nameString as? NSString
var arr = a?.components(separatedBy: " ")
let newStr = arr?[0] as? String
nameString = newStr
if((arr?.count)! > 1)
{
if let secondString = arr?[1]
{
let newStr2 = newStr as? NSString
let secondChar = newStr2?.character(at: 0)
let stringchar:String! = String(secondChar!)
nameString = "\(newStr!) \(stringchar)"
}
}
print("iPhone 5 or less")
}
else
{
print("Greater than iPhone 5")
}
}
}
I don't think anyone should be thinking in Swift 3 any more. Here's a Swift 4 example:
var name = "Veeblefetzer Rumplestiltskin"
if let r = name.range(of: " ", options: .backwards, range: name.startIndex..<name.endIndex) {
name = String(name[name.startIndex..<name.index(r.upperBound, offsetBy: 1)])
}
name // "Veeblefetzer R"
maybe like this?
let fullName = "Dominik Pich"
var parts = fullName.components(separatedBy: " ")
if parts.count > 0,
let lastNameInitial = parts.last?.prefix(1) {
parts[parts.count-1] = String(lastNameInitial)
}
let truncatedName = parts.joined(separator: " ")
//use
print("fullName: \(fullName)")
print("truncatedName: \(truncatedName)")
I'd wrap it in a nice String extension - e.g. a computed property truncateLast
The most helpful answer I've found when using Swift's built in substring command is here: https://stackoverflow.com/a/39677331/5495979
Although, using the substring command still requires you to first obtain a range or an index, so it still requires a couple commands to implement.
So Using my preferred method from the SO answer referenced above I would just grab the index of the first character and use the substring command and cast it to a string:
let index = secondString.index(secondString.startIndex, offsetBy: 0)
let stringChar = String(secondString.substring(to: index))
I also wanted to let you know that there appears to be a logic error in your code when obtaining the first letter of the last name. You unwrap what should be the last name in your string components array with if let secondString = arr?[1] but then don't assign the unwrapped string stored in secondString to newStr2 before parsing newStr2 for the first character in the string. As it appears now when you parse the first character of the string with let secondChar = newStr2?.character(at: 0) you will actually be parsing the first character from the first name (since when assigning newStr2 with let newStr2 = newStr as? NSString you are actually assigning the fist entry from the array of name strings since newStr is only assinged with let newStr = arr?[0] as? String)

How do I assign a variable to a value in a child node from a Firebase Snapshot?

I am trying to minimize the amount of data requests I make to Firebase. I have a snapshot that pulls the following data:
snap (Hole1) {
GreenBackX = "40.196339";
GreenBackY = "-105.07354";
GreenCenterX = "40.196336";
GreenCenterY = "-105.073409";
GreenFrontX = "40.196342";
GreenFrontY = "-105.073283";
Hazard1 = {
CarryX = "40.196839";
CarryY = "-105.07104";
FrontX = "40.196893";
FrontY = "-105.070626";
Name = "R Fwy Bunker";
};
Hazard2 = {
CarryX = "40.196321";
CarryY = "-105.071922";
FrontX = "40.196383";
FrontY = "-105.071573";
Name = "L Fwy Bunker";
};
Hazard3 = {
CarryX = "40.196622";
CarryY = "-105.072935";
FrontX = "40.196662";
FrontY = "-105.072554";
Name = "R Fwy Bunker 2";
};
Hazard4 = {
CarryX = "40.196176";
CarryY = "-105.073545";
FrontX = "40.196225";
FrontY = "-105.073167";
Name = "L Greenside Bunker";
};
HoleH = "258.74";
HoleX = "40.19664";
HoleY = "-105.070484";
}
What I am aiming to do is assign a variable that would be Hazard1\Name. So far, I've only seen working examples in the docs showing how to grab the initial value, which I do like this: let holeX = value?["HoleX"] as? Double ?? 0, but I can't seem to find anything that gets me to the '2nd level' if you will.
There was one example that seemed to say you could do it by referencing it this way: let hazard1Name = value?["Hazard1/Name"] but I couldn't get it to work.
A FIRDataSnapshot contains data from a given Firebase Database location. The data has already been downloaded so there isn't much room for optimizations there, sorry :-(
I think what you might be looking for is:
let ref: FIRDatabaseReference = ...
ref.child("Hazard1").child("Name").observeSingleEvent(of: .value) {
(snapshot) in
let name = snapshot.value as! String
print("Name: \(name)")
}
Otherwise, if you just want to get your data out of the aforementioned snapshot, try this instead:
let snapshot: FIRDataSnapshot = ...
let data = snapshot.value as! [String: Any]
let hazard1 = data["Hazard1"] as! [String: Any]
let name = hazard1["Name"] as! String

Decimal number in text field

I'm trying to get a decimal number from a text field. It only can be a decimal number but if I enter something like 'o,5', than the bullets will spawn a lot faster than every 0.5 second.
My code:
#IBAction func enemyBulletDelayClick(_ sender: AnyObject) {
dismissKeyboard()
let correctNumber = enemyBulletDelayText.text?.replacingOccurrences(of: ",", with: ".")
enemyBulletDelay = Double(correctNumber!)!
enemyBulletDelayText.text = ""
}
(I'm converting each ',' to a '.' for the decimal numbers.)
Otherwise it would give me an error.
I tried to use this code and it worked!
Code:
let formatter = NumberFormatter()
formatter.numberStyle = NumberFormatter.Style.decimal
enemySpawnDelay = (formatter.number(from: enemySpawnDelayText.text!)?.doubleValue)!
If you have a ? you need to unwrap, not put !
There are a bunch of ways to remove . afterwards. Pick whatever you want. This is more focused on the process of what you're doing and then you can decide on using NSNumberFormatter or whatever you want to do.
guard let enemyBulletDelayString = enemyBulletDelayText.text? else {
//put whatever you want to do here if this check doesn't pass
return
}
let numberFormatter = NumberFormatter()
formatter.numberStyle = numberFormatter.Style.decimal
if let formattedNumber = numberFormatter.number(from: enemyBulletDelayString) {
enemySpawnDelay = formattedNumber.doubleValue
} else {
numberFormatter.decimalSeparator = ","
if let formattedNumber = numberFormatter.number(from: enemyBulletDelayString) {
enemySpawnDelay = formattedNumber.doubleValue
}
}
This should work with what you want to do.

How to get exact value from NSNumberFormatter?

From the code below I want convertedN to be to be 99999999 but instead I get 99999998. The problem is that there is a rounding error before I set n. What can I do to get the result I want?
let amount = ".99999999"
let tmpFormatter = NSNumberFormatter()
tmpFormatter.maximumFractionDigits = 8
let n = tmpFormatter.numberFromString(amount)
let decimalAmount = NSDecimalNumber(decimal: n!.decimalValue)
let convertedN = (decimalAmount.decimalNumberByMultiplyingBy(NSDecimalNumber(unsignedLongLong: 100000000))).unsignedLongLongValue
Use doubleValue instead. NSDecimalNumber is rounding the numbers.
let amount = ".99999999"
let tmpFormatter = NSNumberFormatter()
tmpFormatter.maximumFractionDigits = 8
let n = tmpFormatter.numberFromString(amount)
let doubleValue = n!.doubleValue
let convertedN = doubleValue * 100000000
Try like this:
let amount = ".99999999"
let decimalAmount = NSDecimalNumber(string: amount)
let convertedN = decimalAmount.decimalNumberByMultiplyingBy(NSDecimalNumber(string: "100000000")).unsignedLongLongValue // 99,999,999

Resources