我正在尝试使我的API调用现代化,并希望使用NSMassFormatter
。问题很简单。我无法获得任何输出(针对英制语言环境)。 NSMeasurement's
说明正确。
如果提供克,如何使NSMassFormatter
自动显示“ 123磅”重量?
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]
最佳答案
格式化程序不执行任何转换。它仅格式化数量。任何语言中的克仍然是克。
但是,NSMassFormatter确实提供了一种基于千克的便捷方法。因此,例如:
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