NSMassFormatter can't convert grams to lbs (NSUnitMass) or display value

前端 未结 2 2009
死守一世寂寞
死守一世寂寞 2021-01-26 04:57

I am trying to modernize my API calls and want to utilize NSMassFormatter. The problem is simple. I can\'t get any output (aiming for imperial locale). NSMeas

2条回答
  •  梦谈多话
    2021-01-26 05:20

    For anyone coming here in future. You will get correct string if you don't change NSLocale in code. If you need to change it do it in System Settings. stringFromKilograms is the key method which provides metric depended string. Also it is possible to configure NSNumberFormatter to print out rounded values by setting maximumFractionDigits to 0.

    Once you do this you don't need to check for metric system with [[NSLocale currentLocale] usesMetricSystem]

    NSNumber *weightInGrams = @(62403.0);
    NSMassFormatter *formatter = [NSMassFormatter new];
    formatter.forPersonMassUse = YES;
    formatter.unitStyle = NSFormattingUnitStyleShort;
    //formatter.numberFormatter.locale = [[NSLocale alloc] initWithLocaleIdentifier:@"en_US"]; -> source of bug
    formatter.numberFormatter.maximumFractionDigits = 0;
    
    NSString *weightString = [formatter stringFromKilograms:[weightInGrams doubleValue]/1000]; 
    

    Prints correctly:

    (lldb) po weightString3
    138lb
    

提交回复
热议问题