---
title: "Formatters"
slug: formatters
section: tech
date: 2015-05-18T20:18:00.000Z
canonical: https://roland.leth.ro/blog/tech/formatters
---

Since creating formatters is *very* expensive, it's a good idea to have a singleton for them. But what if you have a standard style throughout the app, except a couple of places? Encapsulate it in a `Static` struct and set the required settings before `returning`:

```swift
struct Utils {
  
  class var numberFormatter: NumberFormatter {
    struct Static {
      static let formatter = NumberFormatter()
    }
  	
    Static.formatter.maximumFractionDigits = 2
    Static.formatter.alwaysShowsDecimalSeparator = false
  		
    return Static.formatter
  }
  
}
```
	
Then in the places with a different style:

```swift
let x = Utils.numberFormatter
x.maximumFractionDigits = 3
x.alwaysShowsDecimalSeparator = true
print(x.maximumFractionDigits) // => 3
print(x.alwaysShowsDecimalSeparator) // => true
```

But throughout the app the "default" settings will be returned:

```swift
let y = Utils.numberFormatter
print(y.maximumFractionDigits) // => 2
print(y.alwaysShowsDecimalSeparator) // => false
```

Just be careful with this approach - if you allocate `y` between allocating and using `x`, you will get the default settings for both `x` and `y`:

```swift
let x = Utils.numberFormatter
x.maximumFractionDigits = 3
x.alwaysShowsDecimalSeparator = true

let y = Utils.numberFormatter

print(x.maximumFractionDigits) // => 2
print(x.alwaysShowsDecimalSeparator) // => false
```