-5

I have a formatter

let formatter: NumberFormatter = {
            let formatter = NumberFormatter()
            formatter.numberStyle = .decimal
            formatter.maximumFractionDigits = 8
            return formatter
        }()

I want to let formatter to receive fractions like 1/3, 1/10, 5/115 and convert it into decimal number. Is it possible to fix?

I am expecting to get from 2/3 0.66666667 etc.

Joakim Danielson
  • 43,251
  • 5
  • 22
  • 52
  • Please update your question showing what you have tried. Certainly if you pass `1.0/3.0` into the formatter you will get the correct result. – HangarRash Nov 16 '22 at 19:33
  • if i pass 1.0/3.0 in my formatter, i am getting a result "1". Cause this formatter can only read the first part of this number. – Ростислав Ляпкин Nov 16 '22 at 19:36
  • @РостиславЛяпкин Please, show as a minimal, reproducible example how you are using the formatter. – Sulthan Nov 16 '22 at 19:37
  • TextField("\(matrixA[row-1][column-1])", value: $matrixA[row-1][column-1], formatter: formatter).multilineTextAlignment(.center). Thats an example of using this formatter. User is typing something in TextField. – Ростислав Ляпкин Nov 16 '22 at 19:39
  • For example it can be like TextField("\\(a)", value: a, formatter: formatter). a is a Double – Ростислав Ляпкин Nov 16 '22 at 19:40
  • 2
    Don't post code in comments. Edit your question and add the additional code there (The lack of carriage returns and white space makes anything more than a few characters unreadable in the comments section. Plus future readers shouldn't have to wade through the question and a bunch of comments to understand the question.) – Duncan C Nov 16 '22 at 19:59
  • https://stackoverflow.com/a/61114799/2303865 – Leo Dabus Nov 16 '22 at 21:45

1 Answers1

1

I don't think NumberFormatters are able to parse mathematical expressions like the string "1.0/3.0".

So I believe the answer to your question is no.

If you do a google search on "swift arithmetic expression parser" it looks like there are few open source frameworks that might do what you want.

Duncan C
  • 128,072
  • 22
  • 173
  • 272
  • That's a bit sad, but thank you for you answer – Ростислав Ляпкин Nov 16 '22 at 20:06
  • https://stackoverflow.com/a/61114799/2303865 – Leo Dabus Nov 16 '22 at 21:46
  • That thread shows a `RationalFormatter` that will convert Double values to fractions. The OP needs the opposite: Converting fraction strings to Doubles (which should be easier.) I assume there is a reverse function defined in the Formatter class? (Something like `value(for:String)`.) I’m on an iPad at the moment and don’t have access to the Xcode help system. – Duncan C Nov 17 '22 at 01:59