I am trying to \"nicely\" display fractions in my iPhone application. Previously I have been using a tedious switch statement leading to hardcoded unicode characters for the
There are some included Unicode chars that do give actual fraction appearances, but they're limited to a 1/2, a 1/3 and a 1/4 I think.
If you want this for arbitrary fractions, seems to me like you need a custom view that draws the appropriate look; either through using positioned subviews or drawRect:
.
I'm not aware of any way for a unicode character to have the properties you describe. AFAIK the only thing that distinguishes U+2044 from a regular slash is it's a bit more angled and has little-to-no space on either side, therefore making it nestle up a lot closer to the surrounding numbers.
Here's a page on using the Fraction Slash in HTML, and as you can see it demonstrates that you simply get something like "1⁄10" if you try and use it on your own. It compensates for this by using the <sup>
and <sub>
tags in HTML on the surrounding numbers to get an appropriate display.
In order for you to get this to work in NSString you're going to have to figure out some way to apply superscripting and subscripting to the surrounding numbers yourself.
I know this was a long time ago, but if it helps, there are superscript Unicode characters for all decimal numbers you can use to display arbitrary fractions in most fonts; see answers on a similar question here - https://stackoverflow.com/a/30860163/4522315
Edit:
As per comments, this solution depends on the font you're using. Amsi Pro (left) and other commercial fonts tend to include all the required symbols for superscripts, but the system font (right) does not.
I happened to only want simple fractions for recipes to be converted to Unicode vulgar fractions.
Here is how you can do it:
CGFloat quantityValue = 0.25f;
NSString *quantity = nil;
if (quantityValue == 0.25f) {
// 1/4
const unichar quarter = 0xbc;
quantity = [NSString stringWithCharacters:&quarter length:1];
} else if (quantityValue == 0.33f) {
// 1/3
const unichar third = 0x2153;
quantity = [NSString stringWithCharacters:&third length:1];
} else if (quantityValue == 0.5f) {
// 1/2
const unichar half = 0xbd;
quantity = [NSString stringWithCharacters:&half length:1];
} else if (quantityValue == 0.66f) {
// 2/3
const unichar twoThirds = 0x2154;
quantity = [NSString stringWithCharacters:&twoThirds length:1];
} else if (quantityValue == 0.75f) {
// 3/4
const unichar threeQuarters = 0xbe;
quantity = [NSString stringWithCharacters:&threeQuarters length:1];
}
NSLog(@"%@", quantity);