Irakli Vashakidze
Irakli Vashakidze

Reputation: 61

Int to format %.2f returns unexpected number on iPhone 5

I'm passing 0 as an argument to String(format: "%.2f"), it works on iPhone 5s, se, 6, 6s etc as expected ... However, it stopped working on iPhone 5, I guessed that it was a problem of 32 bit and 64 bit systems, because %f formats 64-bit floating-point number. Wrapped 0 with Double(0) and it worked, result was 0.00.

Can someone explain it in more details ?

Upvotes: 2

Views: 140

Answers (2)

Anuj Panwar
Anuj Panwar

Reputation: 683

You can use swift inbuilt method for a more consistent behavior

// Round the given value to a specified number
// of decimal places
func round(_ value: Double, toDecimalPlaces places: Int) -> Double {
   let divisor = pow(10.0, Double(places))
   return round(value * divisor) / divisor
}

Example:

round(52.3761, toDecimalPlaces: 3) // 52.376

round(52.3761, toDecimalPlaces: 2) // 52.38

Upvotes: 0

Martin R
Martin R

Reputation: 539965

String(format:) uses the same conversion specifications as printf (with some additions like %@ for objects). In particular, the %f conversion expects a Double on the argument list, and passing anything else causes undefined behaviour: It may produce unexpected output or crash.

On a 64-bit platform, passing 0 may work by chance because then Int is a 64-bit integer and thus has the same size as a Double. But even that is not guaranteed to work: passing an integer argument instead of the expected floating pointer number is still undefined behaviour.

Upvotes: 2

Related Questions