Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Swift Numbers Name Text to Int

I just implemented SFSpeechRecognizer, because I want it to dictate some numbers, but the issue that I'm encountering is that if I say "one" the result.bestTranscription.formattedString is "one", but if I say "ten" the result throws "10", how can I manage to get single digit numbers to be represented by the actual number not the symphonic "one".

like image 697
cesar martinez Avatar asked Oct 18 '25 18:10

cesar martinez


1 Answers

You can use NumberFormatter setting numberStyle to .spellOut and use its number(from: String) to convert your string to number. If you need a string from that number just initialise a new string from it. Make sure if you only want to detect English words (not locale sensitive) to set the formatter locale to "en_US_POSIX"

let string = "one"
let numberFormatter = NumberFormatter()
numberFormatter.locale = Locale(identifier: "en_US_POSIX")  // if you dont set locale it will use current locale so it wont detect one if the language it is not english at the devices locale
numberFormatter.numberStyle = .spellOut
numberFormatter.number(from: string)   // 1

Testing another language/locale

let string = "um"
let numberFormatter = NumberFormatter()
numberFormatter.locale = Locale(identifier: "pt_BR")
numberFormatter.numberStyle = .spellOut
numberFormatter.number(from: string)   // 1
like image 181
Leo Dabus Avatar answered Oct 20 '25 08:10

Leo Dabus



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!