Skip to main content

How to Display Fractions in Swift & SwiftUI

How To Display Fractions & Special Characters in Swift & SwiftUI

Using NSLocalizedString to convert double values to strings

NSLocalizedString

NSLocalizedString takes a key and a comment and returns a localized value of a string. You can pass Unicode characters to NSLocalizedString and have your special character displayed inside your app.

Example

To display a fraction, you can use a numerator Unicode, fraction slash Unicode, and a denominator Unicode.

The Unicode for numerators is \u{207x}. The x is a number in this set {0,4,5,6,7,8,9}. A fraction slash is \u{2044}. Lastly, the Unicode for denominators is \u{208x}. Unlike the numerators, the x is a number between 0 and 9. You can create a string variable that holds the fraction 4/5 in SwiftUI with the code below:

There are existing Unicode characters for common fractions such as \u{00BD} for 1/2. You can use the function below to return the common fractions. Pass a double value to the function and it will return the Unicode character equivalent.


You can use the fraction to string function above inside a text view using SwiftUI as the code below:

Thank you for reading.



Comments

Popular posts from this blog

Generating Tweets Using Kim Kardashian’s Twitter.

  For an experiment, I decided to try to generate tweets using the Markov Chains algorithm. I thought it would be interested to see the stream of words that will be picked if I fed the algorithm short and usually unrelated set of texts (Tweets). Often, when working with an algorithm like Markov Chain, you would give it a book or paragraphs that it can learn from, and it would generate some text that would fit the given input. I want the algorithm to represent someone. Picking words from a specific person and see their vocabulary and what can be generated with it. I wanted the person to have light tweets. I didn’t want to pick a political or a controversial figure. So I thought Kim Kardashian West would be the first in my experiment, and there will be more to come. It will be interesting to see patterns and word choices in these generated tweets. Development Recently, I have been developing for iOS more than any other platform, and because of this swift became my go-to language for deve