Formatting decimal places with unknown number

A Float uses a binary (IEEE 754) representation and cannot represent
all decimal fractions precisely. For example,

let x : Float = 123.456

stores in x the bytes 42f6e979, which is approximately
123.45600128173828. So does x have 3 or 14 fractional digits?

You can use NSNumberFormatter if you specify a maximum number
of decimal digits that should be presented:

let fmt = NSNumberFormatter()
fmt.locale = NSLocale(localeIdentifier: "en_US_POSIX")
fmt.maximumFractionDigits = 3
fmt.minimumFractionDigits = 0

println(fmt.stringFromNumber(123)!)      // 123
println(fmt.stringFromNumber(123.4)!)    // 123.4
println(fmt.stringFromNumber(123.45)!)   // 123.45
println(fmt.stringFromNumber(123.456)!)  // 123.456
println(fmt.stringFromNumber(123.4567)!) // 123.457

Swift 3/4 update:

let fmt = NumberFormatter()
fmt.locale = Locale(identifier: "en_US_POSIX")
fmt.maximumFractionDigits = 3
fmt.minimumFractionDigits = 0

print(fmt.string(for: 123.456)!) // 123.456

Leave a Comment