简体   繁体   中英

How to convert 1000 lbs to 1 short ton with current locale in Swift iOS depending on locale?

How do I to convert 1000kg to 1 short ton with current locale in Swift iOS? The input is in kg. I want to output the string in either pounds or short tons depending on if it was over or below 1000 short tons.

However if the default locale was in metric system it should be converted to metric tons. == 0.5 metric tons

I believe there should be a much more simplistic way than to do if statements like the following.

Example:

let x = Measurement(value=1000, unit:UnitMass.kilograms)

if locale is metric and value is 1000kg and above{
// convert it metric tons
}else if not metric system{
   if x converted lbs and is above 1000lbs and above{
      //convert to short tons
   }else{ 
     //remain in lbs
   }
}

Use Locale to see if the device is set to use the metric system. The rest is relatively straightforward:

let kg = Measurement<UnitMass>(value: 1000, unit: .kilograms)

if Locale.current.usesMetricSystem && kg.value > 1000 {
    let tons = kg.converted(to: .metricTons)
} else {
    let lbs = kg.converted(to: .pounds)

    if lbs.value > 1000 {
        let shortTons = lbs.converted(to: .shortTons)
    } else {
        // lbs
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM