NSString representation of fractions using unicode

前端 未结 4 1671
傲寒
傲寒 2021-01-12 15:42

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

4条回答
  •  时光取名叫无心
    2021-01-12 16:29

    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);
    

提交回复
热议问题