Skip to content

Commit

Permalink
significant decimals
Browse files Browse the repository at this point in the history
  • Loading branch information
NSCabezon committed May 26, 2022
1 parent 8b7cf77 commit 9fee63c
Show file tree
Hide file tree
Showing 2 changed files with 16 additions and 0 deletions.
8 changes: 8 additions & 0 deletions Sources/HelpersSPM/Extensions/DoubleExtensions.swift
Original file line number Diff line number Diff line change
Expand Up @@ -5,4 +5,12 @@ public extension Double {
let divisor = pow(10.0, Double(places))
return (self * divisor).rounded() / divisor
}

func stringWithSignificantDecimals(_ places: Int = 3) -> String {
let formatter = NumberFormatter()
let number = NSNumber(value: self)
formatter.minimumFractionDigits = 0
formatter.maximumFractionDigits = places
return String(formatter.string(from: number) ?? "")
}
}
8 changes: 8 additions & 0 deletions Sources/HelpersSPM/Extensions/FloatExtensions.swift
Original file line number Diff line number Diff line change
Expand Up @@ -4,4 +4,12 @@ public extension Float {
var clean1Decimal: String {
return self.truncatingRemainder(dividingBy: 1) == 0 ? String(format: "%.0f", self) : String(format: "%.1f", self)
}

func stringWithSignificantDecimals(_ places: Int = 3) -> String {
let formatter = NumberFormatter()
let number = NSNumber(value: self)
formatter.minimumFractionDigits = 0
formatter.maximumFractionDigits = places
return String(formatter.string(from: number) ?? "")
}
}

0 comments on commit 9fee63c

Please sign in to comment.