Dynamic trim double [closed] - swift

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 1 year ago.
Improve this question
What I want.
A: $1.10 = $1.1
B: $0.10101010101 = $0.101010
What I've tried
Solution one -
String(format: "%.6f", price)
This will do the following:
A: $1.100000
B: $0.1010101
So B is gets the correct outcome but A gets more decimals.
Solution two -
numberFormatter.numberStyle = .decimal
This gives the following outcome
A: $1.1
B: $0.1
So here A is correct but B gets rounded up.

This code will work for removing trailing zeros
let distanceFloat1: Float = 1.10
let distanceFloat2: Float = 0.10101010101
print("Value \(distanceFloat1.clean)")
print("Value \(distanceFloat2.clean)")
extension Float {
var clean: String {
return self.truncatingRemainder(dividingBy: 1) == 0 ? String(format: "%.0f", self) : String(self)
}
}
Output
Value 1.1
Value 1.101010
if you want to remove trailing zeros, also want to remove decimals after x place use
Swift - Remove Trailing Zeros From Double

I removed the trailing zeros using Ben's answer.
var stringWithoutZeroFraction: String {
return truncatingRemainder(dividingBy: 1) == 0 ? String(format: "%.0f", self) : String(self)
}

Related

Building a string by repeating a single character [duplicate]

This question already has answers here:
Repeating String in Swift
(8 answers)
Closed 5 months ago.
To size a view, I needed to build a string by repeating a single character. I came up with the following:
var str = ""
for _ in 0 ..< length {
str.append("W")
}
I also came up with a functional alternative:
let str = (0 ..< digits).reduce("") { (result, _) -> String in
result + "0" // assuming 0 is the most wide number
}
Both feel a bit verbose. Is there a shorter way or a built-in function in Swift?
Use init(repeating:count:)
var str = String(repeating: "w", count: length)

How to check if the result of an operation equals an Integer? [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 2 years ago.
Improve this question
I'm super new with Swift (and programming). I need to compare if the result of a Remainder Operator (modulo operator) equals an integer.
This is my code:
if Int.random(in: 1...1000) % 4 >= "This number" {
print ("OK")
} else {
print ("WRONG")
}
If "This number" is replaced by an actual number e.g. 100 it works fine.
But if replaced by Int it crashes displaying: Type 'Int.Type' cannot conform to 'BinaryInteger'; only struct/enum/class types can conform to protocols
You have to compare Int with Int, not String or Int type (Int.Type). If you want to declare a value that you will use for comparison you can declare it as variable. To compare if it is equal use == operator.
let thisNumber: Int = 3 // or any other value
if Int.random(in: 1...1000) % 4 == thisNumber {
print ("OK")
} else {
print ("WRONG")
}
now both Int.random(in: 1...1000) % 4 and thisNumber is Int so you can compare them without getting an error.

Round Double value in swift with addition before decimal [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 3 years ago.
Improve this question
i have double value 70514.94971385633, now I want it to round the value and make it 70515.00. I have tried command rounded(), but it only rounds value after the decimal. How I can round value after the decimal and add the nearest value to a number before decimal? this is my code for rounding the value,
let totalBidValue = self.minBid / usdToAED!
let roundedValue = totalBidValue.rounded()
but it shows result 70514.95, i want it to add it before decimal value like 70515.00
Just small change in your code
let totalBidValue = self.minBid / usdToAED!
let roundedValue = totalBidValue.round()
or
let roundedValue = totalBidValue.rounded(.up)
Use ceil(_:) to get that working,
let value = 70514.94971385633
let result = ceil(value)
print(result) //70515.0
Use round()
let myDoubleValue = 70514.94971385633
let roundedOffValue = round(myDoubleValue)
print(roundedOffValue) // 70515.0
Your code is almost perfect...
let totalBidValue = self.minBid / usdToAED!
let roundedValue = totalBidValue.rounded(.toNearestOrAwayFromZero)
just add .toNearestOrAwayFromZero in your code

How do I convert Float to Int When Necessary? [duplicate]

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

Why dosn't this objective-c if statement work? [closed]

Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
Questions asking for code must demonstrate a minimal understanding of the problem being solved. Include attempted solutions, why they didn't work, and the expected results. See also: Stack Overflow question checklist
Closed 9 years ago.
Improve this question
I's sorry but I'm new to Xcode and coding.
Im trying to create an If statement so that if label 3 = or greater then 20 label 4 = 0, else if lower then 20 it = 1 and if lower then 18.5 its = 2.
this is my code for that:
if (_label3.text >= #"20") {_label4.text = #"0";}
else if (_label3.text < #"20") {_label4.text = #"1";}
else if (_label3.text <= #"18.5") {_label4.text = #"2";}
I'm not sure what is going wrong, but i am getting this error 'Direct comparison of String literal has undefined behavior' and Xcode wont let me build the app.
Thank for your Help
you are using arithmetic operations on strings. that for sure makes no sense
create a float from the textfield input
if ([_label3.text floatValue] >= 20.0) {_label4.text = #"0";}
aslo you have to change the 1st and 2nd else branch, a the last one will never be called, as if it is true, the fist one is also be true.
float value = [_label3.text floatValue];
if (value > 20.0) {_label4.text = #"0";}
else if (value <= 18.5) {_label4.text = #"2";}
else if (value < 20.0) {_label4.text = #"1";}
label.text is string value and you cant compare string to int. Change the string to int and then compare like this
if([_label3.text intValue] >= 20){
_label4.text = #"0";
}
Hope this helps.