How to split Doubles and Floats into whole numbers and fractions in Swift

by Joey deVilla on February 5, 2016

modf

Lately, I’ve been seeing a number of half-baked implementations of a function that splits a floating-point number (Floats, Doubles, and the like) into a whole number and fraction part. For example, given the value 3.141592, it should return:

  • The whole number part: 3, and
  • the fractional part: 0.141592.

There’s no need to come up with your own implementation: there’s a function in C’s math library, and many programming languages, Swift included, give you access to it. It’s called modf, and in Swift, it works like this:

Since C doesn’t have a tuple type, you call modf differently. Here’s the function’s signature:

Its return value is the fractional part, and the whole number value is put into an extra variable whose address you provide. If you’re working in Swift and feeling homesick for the pointer-y stuff you have to do in C, you can call modf this way:

But seriously: do it the first way. It’s more Swift-like (Swift-esque? Swifty?).

Leave a Comment

Previous post:

Next post: