Categories

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

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:

```// modf returns a 2-element tuple,
// with the whole number part in the first element,
// and the fraction part in the second element
let splitPi = modf(3.141592)
splitPi.0 // 3.0
splitPi.1 // 0.141592```

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

`double modf(double x, double *integer)`

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:

```var wholeNumberPart: Double = 0.0
let fractionalPart = modf(3.141592, &wholeNumberPart)
fractionalPart  // 0.141592
wholeNumberPart // 3.0```

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