Skip to content

Commit

Permalink
Localize the Percent description (#8)
Browse files Browse the repository at this point in the history
  • Loading branch information
magauran authored and sindresorhus committed Nov 13, 2019
1 parent 5f650f1 commit 8720f10
Show file tree
Hide file tree
Showing 2 changed files with 37 additions and 3 deletions.
10 changes: 9 additions & 1 deletion Sources/Percent/Percent.swift
Original file line number Diff line number Diff line change
Expand Up @@ -131,7 +131,15 @@ extension Percent: Comparable {
}

extension Percent: CustomStringConvertible {
public var description: String { "\(String(format: "%g", rawValue))%" }
internal static var formatter: NumberFormatter = {
let formatter = NumberFormatter()
formatter.numberStyle = .percent
return formatter
}()

public var description: String {
Self.formatter.string(for: fraction) ?? "\(String(format: "%g", rawValue))%"
}
}

// swiftlint:disable static_operator
Expand Down
30 changes: 28 additions & 2 deletions Tests/PercentTests/PercentTests.swift
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,6 @@ final class PercentTests: XCTestCase {
XCTAssertEqual(10%, 10%)
XCTAssertEqual(-10% / 2, -5%)
XCTAssertEqual(1.1%.rawValue, 1.1)
XCTAssertEqual("\(1%)", "1%")
XCTAssertEqual(10% + 5.5%, 15.5%)
XCTAssertEqual((40% + 93%) * 3, 399%)
XCTAssertEqual(50%.of(200), 100)
Expand All @@ -21,7 +20,6 @@ final class PercentTests: XCTestCase {

XCTAssertEqual(Percent(fraction: 0.5), 50%)
XCTAssertEqual(50%.fraction, 0.5)
XCTAssertEqual("\(50%)", "50%")

XCTAssertTrue(30% > 25%)
}
Expand Down Expand Up @@ -87,4 +85,32 @@ final class PercentTests: XCTestCase {

XCTAssertEqual(string, "{\"alpha\":1}")
}

func testStringConversion() {
let formatter = NumberFormatter()
formatter.numberStyle = .percent

formatter.locale = Locale(identifier: "ru")
Percent.formatter = formatter
XCTAssertEqual("\(50%)", formatter.string(for: 50%.fraction))
XCTAssertEqual("\(1%)", formatter.string(for: 1%.fraction))

formatter.locale = Locale(identifier: "tr")
Percent.formatter = formatter
XCTAssertEqual("\(50%)", formatter.string(for: 50%.fraction))
XCTAssertEqual("\(1%)", formatter.string(for: 1%.fraction))

formatter.locale = Locale(identifier: "eu")
Percent.formatter = formatter
XCTAssertEqual("\(50%)", formatter.string(for: 50%.fraction))
XCTAssertEqual("\(1%)", formatter.string(for: 1%.fraction))

formatter.locale = Locale(identifier: "ar")
Percent.formatter = formatter
XCTAssertEqual("\(50%)", formatter.string(for: 50%.fraction))
XCTAssertEqual("\(1%)", formatter.string(for: 1%.fraction))

formatter.locale = Locale.current
Percent.formatter = formatter
}
}

0 comments on commit 8720f10

Please sign in to comment.