Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to format a Swift 3 nsmeasurement string to at most 2 decimal places after conversion?

Tags:

swift

I would like to know how to round nsmeasurement after conversion from a unitmass. From Kilograms to Pounds for example and rounding to the 2nd decimal place instead of giving me the exact.

 var x = Measurement(value:19, unit: UnitMass.kilograms)
 x.convert(to:UnitMass.Pounds)
 x.description // "41.8878639834918 lb"

I'd like it to be 41.89

like image 878
user805981 Avatar asked Dec 24 '16 12:12

user805981


1 Answers

By using a MeasurementFormatter:

var x = Measurement(value:19, unit: UnitMass.kilograms)
x.convert(to:UnitMass.pounds)
x.description // 41.8878639834918 lb

let m = MeasurementFormatter()
m.numberFormatter.maximumFractionDigits = 2
m.string(from: x) // 41.89 lb
like image 57
luk2302 Avatar answered Oct 02 '22 16:10

luk2302