FractionFormatter

1.0

Swift FractionFormatter, like NumberFormatter, but outputs fractions.
davidwkeith/FractionFormatter

What's New

1.0

2024-06-05T19:06:26Z

Full Changelog: 0.9.1...1.0

FractionFormatter

Swift Version Compatibility Badge Platform Compatibility Badge

A subclass of Apple's NumberFormatter that outputs pretty-printed Unicode fractions rather than decimals.

Adding FractionFormatter to your project

In Xcode, use the File:Swift Packages:Add Package Dependency… menu command and enter https://gitlab.com/davidwkeith/fractionformatter.git

Usage

FractionFormatter is a direct replacement for NumberFormatter and is used the same way:

let fractionFormatter = FractionFormatter()
fractionFormatter.string(from: NSNumber(value: 0.5)) // "½"
fractionFormatter.string(from: NSNumber(value: 0.123)) // "¹²³⁄₁₀₀₀"

There are of course some connivance methods that make working with strings containing fractions easier:

fractionFormatter.double(from: "1 ½") // 1.5
fractionFormatter.double(from: "1 1/2") // 1.5
fractionFormatter.string(from: "1 1/2") // "1 ½"
fractionFormatter.string(from: "1 ½", as: .BuiltUp) // 1 1/2

Filing feature requests and issues

The source is hosted on GitLab and mirrored on GitHub. If you find an issues or have a feature request, you can file it here.

Known Issues

Radar FB7644708 - Pluralization and number formatting

When combined with Apple's MeasurementFormatter there are issues with pluralization. For example, using NumberFormatter to format fractional feet, it will output "0.5 feet", read as "zero point five feet", but if you substitute FractionFormatter then the output is "½ feet", which is not how it is normally written in English. Normally we say "half a foot", or more formally "one half of a foot" and thus write the singular form.

The workaround it to pull the symbol from the measurement and substitute the pluralized symbol when the measurement is between -1 and 1.

Description

  • Swift Tools 5.0.0
View More Packages from this Author

Dependencies

  • None
Last updated: Sun Dec 15 2024 01:36:06 GMT-1000 (Hawaii-Aleutian Standard Time)