TransWikia.com

Swift - Negative string to integer conversion not being parsed correctly

Stack Overflow Asked by methodical on December 16, 2021

This is a fairly simple question but has been causing me a multitude of issues. I have a integer which comes from my API endpoint in a string format, as this: "-43.47" (for example). I need to display the number differently (as they’re percentages of change) in my SwiftUI view. The code I have been trying to use for this is below;

if((Int(self.percentageChange) ?? 0) >= 0) {
   Text("+ " + String(self.percentageChange + "%")).foregroundColor(Color.green)
} else {
   Text("- " + String((0 - Int(self.percentageChange)) + "%")).foregroundColor(Color.red)
}

The problem is, whether or not the string number is a negative integer, it gets parsed as a positive integer and appears as so in my actual view (without an actual photo, but take my word for it): "+ -43.47%", and I have no idea why. Obviously -43.47 is less than 0, so it should be caught by the exception, but for some strange reason, perhaps as a result of my application of parenthesis or otherwise, it isn’t being caught as such.

3 Answers

Use NumberFormatter:

let numberFormatter = NumberFormatter()
numberFormatter.numberStyle = .percent
numberFormatter.multiplier = 1
numberFormatter.maximumFractionDigits = 2
numberFormatter.positivePrefix = "+"

---

let percentageChange = Double(self.percentageChange) ?? 0
let color = percentageChange < 0 ? Color.red : Color.green

Text(numberFormatter.string(for: percentageChange)).foregroundColor(color)

Note that this will make your number formatted correctly and properly localized.

Answered by Sulthan on December 16, 2021

Isn't it easier to check the string for the leading minus sign

if self.percentageChange.hasPrefix("-") {
   Text(self.percentageChange + "%").foregroundColor(Color.red)
} else {
   Text("+ " + self.percentageChange + "%").foregroundColor(Color.green)
}

Answered by vadian on December 16, 2021

You just need to use the Float initializer to convert floating-point string to float and then compare.

Replace:

if((Int(self.percentageChange) ?? 0) >= 0) {

With:

if((Float(percentageChange) ?? 0) >= 0) {

The better alternative is to do this:

if !self.percentageChange.hasPrefix("-") {

Answered by Frankenstein on December 16, 2021

Add your own answers!

Ask a Question

Get help from others!

© 2024 TransWikia.com. All rights reserved. Sites we Love: PCI Database, UKBizDB, Menu Kuliner, Sharing RPP