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:
@State var num = " | |
\(NSLocalizedString("\u{2074}", comment: "Numerators - 4")) | |
\(NSLocalizedString("\u{2044}", comment: "fraction slash")) | |
\(NSLocalizedString("\u{2085}", comment: "Denominator - 5")) | |
" |
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.
func fractionToString (fraction: Double) -> String { | |
switch fraction { | |
case 0.125..<0.126: | |
return NSLocalizedString("\u{215B}", comment: "1/8") | |
case 0.25..<0.26: | |
return NSLocalizedString("\u{00BC}", comment: "1/4") | |
case 0.33..<0.34: | |
return NSLocalizedString("\u{2153}", comment: "1/3") | |
case 0.5..<0.6: | |
return NSLocalizedString("\u{00BD}", comment: "1/2") | |
case 0.66..<0.67: | |
return NSLocalizedString("\u{2154}", comment: "2/3") | |
case 0.75..<0.76: | |
return NSLocalizedString("\u{00BE}", comment: "3/4") | |
default: | |
return "\(fraction)" | |
} | |
} |
You can use the fraction to string function above inside a text view using SwiftUI as the code below:
struct ContentView: View { | |
@State var half : Double = 1/2 | |
var body: some View { | |
VStack { | |
Text("\(fractionToString(fraction: half))") | |
.font(.system(size: 30)) | |
} | |
} | |
func fractionToString (fraction: Double) -> String { | |
switch fraction { | |
case 0.125..<0.126: | |
return NSLocalizedString("\u{215B}", comment: "1/8") | |
case 0.25..<0.26: | |
return NSLocalizedString("\u{00BC}", comment: "1/4") | |
case 0.33..<0.34: | |
return NSLocalizedString("\u{2153}", comment: "1/3") | |
case 0.5..<0.6: | |
return NSLocalizedString("\u{00BD}", comment: "1/2") | |
case 0.66..<0.67: | |
return NSLocalizedString("\u{2154}", comment: "2/3") | |
case 0.75..<0.76: | |
return NSLocalizedString("\u{00BE}", comment: "3/4") | |
default: | |
return "\(fraction)" | |
} | |
} | |
} |
Thank you for reading.
Comments
Post a Comment