This question already has answers here:
Swift - How to remove a decimal from a float if the decimal is equal to 0?
(15 answers)
Closed 6 years ago.
So, I'm pretty new to swift and Xcode and might be missing something obvious, but I've done a bit of research, and can't find my answer.
My code is:
for number in currentList {
listPreview.text = "\(listPreview.text!) \(String(number))"
}
The problem is, the Numbers in currentList are Floats. But if my user were to input a number that isn't a float, it will display as:
"UsersNumber".0
I want it to display as just:
"UsersNumber"
However, if the number the user gave me was a float, say... 1.2, I would still want it to display as 1.2 .
is there some kind of extension that can do this?
Like an if-statement saying
if number.isUselessFloat {
code
}
Thanks in advance,
-Another Nooby user
let number1 = 1.0
let number2 = 1.2
let str = String(format: number1 == floor(number1) ? "%.0f":"%.1f", number1)
print(str)
//prints 1
let str2 = String(format: number2 == floor(number2) ? "%.0f":"%.1f", number2)
print(str2)
//prints 1.2
Related
This question already has answers here:
Is the Swift divide "/" operator not working or have I missed something?
(3 answers)
Division not working properly in Swift
(3 answers)
Closed 1 year ago.
I have created a for loop in which I calculate a few values.
for i in 1...100{
let xValue = i/100
print(xValue) // returns 0 every time except when i == 100
}
This is a recreation of a part of that for loop. Why is it that I do not get the right value for 'xValue'?
For info I have also tried the following:
let xValue: Float = Float(i/100)
And that doesn't work either, despite me being very specific. I must have forgotten something basic about these arithmetic
operators in swift.
When you divide an Int by an Int, the result will be rounded down. Use a floating point type, like Double or Float for more precision.
for i in 1...100 {
let xValue = Float(i)/100
print(xValue)
}
To address your attempted solution - when you do:
let xValue: Float = Float(i/100)
The Int result is first computed in i/100 (and rounded down to 0) then you are casting to a Float.
Therefore, we cast i to a Float before the division so the result is computed as a Float.
Since i and 100 are both integer values, / will do integer division and the result will be truncated to 0.
Even when you do let xValue: Float = Float(i/100), the result of division inside the parentheses is already truncated to 0 before the value can be converted to a Float.
Convert i to a floating-point value before dividing to prevent the result from being truncated.
for i in 1...100{
let xValue = Float(i)/100
print(xValue)
}
This question already has answers here:
In Swift 3, how to calculate the factorial when the result becomes too high?
(2 answers)
BigInteger equivalent in Swift?
(6 answers)
Closed 3 years ago.
I am solving a question from HackerRank which asks to print the value of extra-long factorials that can't be stored even in a 64-bit long variable.
I am using NSDecimalNumber to store the value. However, even in this case, the final result is rounded off.
func extraLongFactorials(n: Int) -> Void
{
var factorial: NSDecimalNumber = 1
for index in 1...n
{
let indexInNSDecimal = NSDecimalNumber(value: index)
factorial = factorial.multiplying(by: indexInNSDecimal)
}
let factorialWithoutRounding = factorial.description(withLocale: nil)
print(factorialWithoutRounding)
}
print(extraLongFactorials(n: 45)) // 119622220865480194561963161495657715064000000000000000000
However, the result should be 119622220865480194561963161495657715064383733760000000000.
This link talks about using description(withLocale:).
NSDecimalNumber round long numbers
However, it does not clearly explain how to use the description(withLocale:) method.
I also went through the apple doc https://developer.apple.com/documentation/foundation/nsdecimalnumber/1412789-description. But it also does not explain clearly how to use it.
Can someone please discuss this method in detail.
This question already has answers here:
Get nth character of a string in Swift
(47 answers)
Closed 3 years ago.
I am trying to extract a partial String from a given input String in Swift5. Like the letters 2 to 5 of a String.
I was sure, something as simple as inputString[2...5]would be working, but I only got it working like this:
String(input[(input.index(input.startIndex, offsetBy: 2))..<(input.index(input.endIndex, offsetBy: -3))])
... which is still using relative positions (endIndex-3 instead of position #5)
Now I am wondering where exactly I messed up.
How do people usually extract "cde" from "abcdefgh" by absolute positions??
I wrote the following extension for shorthand substrings without having to deal with indexes and casting in my main code:
extension String {
func substring(from: Int, to: Int) -> String {
let start = index(startIndex, offsetBy: from)
let end = index(start, offsetBy: to - from + 1)
return String(self[start ..< end])
}
}
let testString = "HelloWorld!"
print(testString.substring(from: 0, to: 4)) // 0 to 4 inclusive
Outputs Hello.
This question already has answers here:
Convert Float to Int in Swift
(15 answers)
Closed 5 years ago.
I understand that Int() is how to make something and integer but this doesn't work when using it with speed. Here is my code:
var speed: CLLocationSpeed = CLLocationSpeed()
speed = location.speed * 2.23694
if location.speed < 1 {
speedLabel.text = "0"
}
else {
speedLabel.text = "\(speed)"
}
Just wondering how to make my speed (mph) into an integer because currently I am getting 2 decimal points which make my app look messy. Thanks in advance
Use a rounding function. In action:
22> round (1.6)
$R10: Double = 2
23> Int(round (1.6))
$R11: Int = 2
This question already has answers here:
What is the difference between ":" and "=" in Swift?
(3 answers)
Closed 7 years ago.
I have been programming in Swift for quite a while. But still I haven't got down the whole of the basics and haven't understood the difference between '=' and ':'. We use these to declare variables. But what is the difference between equal to and a colon while programming in Swift? Any help will be appreciated!
With : you are declaring a type and with = you are assigning a value.
Check out the section "Type Annotations" in the Apple Swift guide.
In response to the comment:
when we use = also while declaring the type. For example- var anyVariable = Int. In this we are declaring the type, isn't it? Pardon me if I am wrong. – ojassethi
This is because the type will automatically recognized.
For example all Strings are declared with quotation marks
let myString = "Hello" // The right Value is a String, so the variable is of the type string
While on the other hand it could mistake a value if you are not precisely using =
let myDouble = 1 // myDouble is an Int! not a Double, because for the compiler 1 is an Int
let myDouble: Double = 1 // Now myDouble is a Double
let myDouble = 1.0 // Now myDouble also is a Double