iosobjective-cnsmeasurementformatter

How can I handle the MeasurementFormatter using the kilometersPerHour UnitType?


I need to display the integer from km/h values using the MeasurementFormatter on Objective-C.

Is there any sample available?

NSMeasurementFormatter *formatter = [[NSMeasurementFormatter alloc] init];
formatter.unitStyle = MKDistanceFormatterUnitStyleAbbreviated;

Solution

  • Here is some example

        NSMeasurementFormatter *formatter = [[NSMeasurementFormatter alloc] init];
        formatter.unitStyle = NSFormattingUnitStyleMedium;
        formatter.locale = [NSLocale localeWithLocaleIdentifier:@"en_US"];
    
        // format 100 km/h
    
        formatter.unitOptions = NSMeasurementFormatterUnitOptionsProvidedUnit;
        NSUnitSpeed *speed = [NSUnitSpeed kilometersPerHour];
        NSString *speedString = [formatter stringFromMeasurement:[[NSMeasurement alloc] initWithDoubleValue:100.0 unit:speed]];
    
        NSLog(@"kilometers %@", speedString);
    
        // format 100 mph
    
        formatter.unitOptions = NSMeasurementFormatterUnitOptionsProvidedUnit;
        speed = [NSUnitSpeed milesPerHour];
        speedString = [formatter stringFromMeasurement:[[NSMeasurement alloc] initWithDoubleValue:100.0 unit:speed]];
    
        NSLog(@"miles %@", speedString);
    
        // convert 100 km/h to 62.137 mph for en_US locale
    
        formatter.unitOptions = NSMeasurementFormatterUnitOptionsNaturalScale;
        speed = [NSUnitSpeed kilometersPerHour];
        speedString = [formatter stringFromMeasurement:[[NSMeasurement alloc] initWithDoubleValue:100.0 unit:speed]];
    
        NSLog(@"miles to kilometers %@", speedString);