-1

I parse Int object from API, but it's too long. So I want to cut it to two characters. I parse "6700000", but I want it to be "$6.7 m", or I parse "90000000", but I want to show "$90 m".

struct MillionView: View {
    @State var rockets = [RocketInfo]()
    
    var body: some View {
        List(rockets) { rocket in
            HStack {
                Text("Cost per launch")
                Spacer()
                Text("$\(rocket.costPerLaunch) m")
            }
        }
        .onAppear {
            InfoApi().getRockets { rockets in
                self.rockets = rockets
            }
        }
    }
}

struct MillionView_Previews: PreviewProvider {
    static var previews: some View {
        MillionView()
    }
}
bowtie
  • 29
  • 6
  • I think the "cut the string to first two letters" is likely not the approach you'll want to take. Even in your example, you show that in one circumstance, you'd need a decimal and in another you wouldn't -- simply trimming a string wouldn't do that. Instead, use a number (convert to it if it isn't one yet), then divide by 1,000,000 and trim to appropriate number of decimals (this may be helpful for that: https://stackoverflow.com/questions/27338573/rounding-a-double-value-to-x-number-of-decimal-places-in-swift) – jnpdx Apr 08 '22 at 00:05
  • If you just want to with on strings, the prefix() method of string instance is what you need. – Ptit Xav Apr 08 '22 at 05:59
  • Thank you so much for your answers, (@jnpdx) and (@Ptit Xav), but the reality is that I tried all day to understand how to solve this problem, and even wrote a question on stackoverflow, and then for a moment stopped being stupid and just divided the parsed values by 1000000‍♂️ Text("$\(rocket.costPerLaunch / 1000000) m") – bowtie Apr 08 '22 at 18:28
  • Thank you, @jnpdx, you were right, and I was just inattentive‍♂️ – bowtie Apr 08 '22 at 19:52

1 Answers1

0

I was inattentive, but then I realized that the answer was:

Text("$\(rocket.costPerLaunch / 1000000) m")

I just divided the value by a million and got the desired result.

bowtie
  • 29
  • 6