Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

NSString representation of fractions using unicode

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 vulgar fractions, but I have learnt about the unicode fraction slash character which, if I am understanding it correctly, should mean that I can create a string as follows:

[NSString stringWithFormat:@"%i\u2044%i",numerator,denominator];

And the "renderer" will automatically print it with a smaller, superscriped numerator and subscripted denominator. However, the above code just gives me the standard 1/2 appearance. I am using drawAtPoint to put the string on the screen. I have experimented with decomposedStringUsingCanonicalMapping and precomposedStringUsingCanonicalMapping but to be honest the documentation lost me.

Should this be working or does NSString drawing not cope with this?

like image 236
jrturton Avatar asked Aug 02 '11 20:08

jrturton


2 Answers

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);
like image 132
Cameron Lowell Palmer Avatar answered Oct 20 '22 19:10

Cameron Lowell Palmer


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.

like image 21
Lily Ballard Avatar answered Oct 20 '22 18:10

Lily Ballard