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

十年热恋 提交于 2019-12-04 07:09:41

问题


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). NSMeasurement's description is correct.

How to make NSMassFormatter to display "123 lbs" weight automatically if I provide grams?

NSNumber *weightInGrams = @(62453.0);

NSMassFormatter *weightFormatter = [NSMassFormatter new];
weightFormatter.forPersonMassUse = YES;
weightFormatter.numberFormatter.locale = [NSLocale localeWithLocaleIdentifier:@"en_UK"];

NSMeasurement *weightMeasurement = [[NSMeasurement alloc] initWithDoubleValue:[weightInGrams doubleValue] unit:[NSUnitMass grams]];

NSString *weightString = [weightFormatter unitStringFromValue:[weightInGrams doubleValue] unit:NSMassFormatterUnitPound];
NSLog(@"%@", weightMeasurement);
NSLog(@"%@", weightString);

2019-03-26 17:23:37.535156+0100 testasa[65239:9291466] <NSMeasurement: 0x60800002d020> value: 62453.000000 unit: g
2019-03-26 17:23:37.535169+0100 testasa[65239:9291466] 

回答1:


The formatter does not perform any conversions. It merely formats a quantity. A gram is still a gram in any language.

However, NSMassFormatter does provide a convenience method based on kilograms. So for example:

let grams = 62453.0
let measurement = Measurement(value: grams, unit: UnitMass.grams)
let kilos = measurement.converted(to: .kilograms)
let formatter = MassFormatter()
formatter.isForPersonMassUse = true
let s = formatter.string(fromKilograms: kilos.value)
print(s) // "137.685 lb” on my machine



回答2:


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


来源:https://stackoverflow.com/questions/55361937/nsmassformatter-cant-convert-grams-to-lbs-nsunitmass-or-display-value

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!